From 029dba5a4078bc1e9dc262d24aaa481936af49d3 Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Tue, 10 Feb 2004 09:33:39 +0000 Subject: Make reversed() transparent with respect to length. --- Lib/test/test_enumerate.py | 4 ++++ Objects/enumobject.c | 14 +++++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/Lib/test/test_enumerate.py b/Lib/test/test_enumerate.py index ab1a60d..00ecbcc 100644 --- a/Lib/test/test_enumerate.py +++ b/Lib/test/test_enumerate.py @@ -145,6 +145,10 @@ class TestReversed(unittest.TestCase): 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) diff --git a/Objects/enumobject.c b/Objects/enumobject.c index 3aac680..55595ce 100644 --- a/Objects/enumobject.c +++ b/Objects/enumobject.c @@ -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) { @@ -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 = { @@ -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 */ -- cgit v0.12