Make reversed() transparent with respect to length.

This commit is contained in:
Raymond Hettinger 2004-02-10 09:33:39 +00:00
parent 5cab2e3a88
commit 029dba5a40
2 changed files with 17 additions and 1 deletions

View File

@ -145,6 +145,10 @@ class TestReversed(unittest.TestCase):
s = 'hello' s = 'hello'
self.assertEqual(list(reversed(reversed(s))), list(s)) self.assertEqual(list(reversed(reversed(s))), list(s))
def test_len(self):
s = 'hello'
self.assertEqual(len(reversed(s)), len(s))
def test_main(verbose=None): def test_main(verbose=None):
testclasses = (EnumerateTestCase, SubclassTestCase, TestEmpty, TestBig, testclasses = (EnumerateTestCase, SubclassTestCase, TestEmpty, TestBig,
TestReversed) TestReversed)

View File

@ -230,6 +230,12 @@ reversed_next(reversedobject *ro)
return item; return item;
} }
static int
reversed_len(reversedobject *ro)
{
return PyObject_Size(ro->seq);
}
static PyObject * static PyObject *
reversed_reverse(reversedobject *ro, PyObject *unused) reversed_reverse(reversedobject *ro, PyObject *unused)
{ {
@ -244,6 +250,12 @@ PyDoc_STRVAR(reversed_doc,
static PyMethodDef reversed_methods[] = { static PyMethodDef reversed_methods[] = {
{"__reversed__", (PyCFunction)reversed_reverse, {"__reversed__", (PyCFunction)reversed_reverse,
METH_NOARGS, reversed_doc}, METH_NOARGS, reversed_doc},
{NULL, NULL} /* sentinel */
};
static PySequenceMethods reversed_as_sequence = {
(inquiry)reversed_len, /* sq_length */
0, /* sq_concat */
}; };
PyTypeObject PyReversed_Type = { PyTypeObject PyReversed_Type = {
@ -260,7 +272,7 @@ PyTypeObject PyReversed_Type = {
0, /* tp_compare */ 0, /* tp_compare */
0, /* tp_repr */ 0, /* tp_repr */
0, /* tp_as_number */ 0, /* tp_as_number */
0, /* tp_as_sequence */ &reversed_as_sequence, /* tp_as_sequence */
0, /* tp_as_mapping */ 0, /* tp_as_mapping */
0, /* tp_hash */ 0, /* tp_hash */
0, /* tp_call */ 0, /* tp_call */