Skip to content

Commit

Permalink
Make reversed() transparent with respect to length.
Browse files Browse the repository at this point in the history
  • Loading branch information
rhettinger committed Feb 10, 2004
1 parent 5cab2e3 commit 029dba5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
4 changes: 4 additions & 0 deletions Lib/test/test_enumerate.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,10 @@ def test_double_reverse(self):
s = 'hello'
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):
testclasses = (EnumerateTestCase, SubclassTestCase, TestEmpty, TestBig,
TestReversed)
Expand Down
14 changes: 13 additions & 1 deletion Objects/enumobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,12 @@ reversed_next(reversedobject *ro)
return item;
}

static int
reversed_len(reversedobject *ro)
{
return PyObject_Size(ro->seq);
}

static PyObject *
reversed_reverse(reversedobject *ro, PyObject *unused)
{
Expand All @@ -244,6 +250,12 @@ PyDoc_STRVAR(reversed_doc,
static PyMethodDef reversed_methods[] = {
{"__reversed__", (PyCFunction)reversed_reverse,
METH_NOARGS, reversed_doc},
{NULL, NULL} /* sentinel */
};

static PySequenceMethods reversed_as_sequence = {
(inquiry)reversed_len, /* sq_length */
0, /* sq_concat */
};

PyTypeObject PyReversed_Type = {
Expand All @@ -260,7 +272,7 @@ PyTypeObject PyReversed_Type = {
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
&reversed_as_sequence, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
Expand Down

0 comments on commit 029dba5

Please sign in to comment.