Let reversed() work with itself.

This commit is contained in:
Raymond Hettinger 2004-02-08 10:49:42 +00:00
parent 8a1a594590
commit 06353f76be
3 changed files with 17 additions and 1 deletions

View File

@ -22,6 +22,7 @@ extern "C" {
typedef struct {
PyObject_VAR_HEAD
PyObject **ob_item;
int allocated;
} PyListObject;
PyAPI_DATA(PyTypeObject) PyList_Type;

View File

@ -141,6 +141,10 @@ class TestReversed(unittest.TestCase):
x = xrange(1)
self.assertEqual(type(reversed(x)), type(iter(x)))
def test_double_reverse(self):
s = 'hello'
self.assertEqual(list(reversed(reversed(s))), list(s))
def test_main(verbose=None):
testclasses = (EnumerateTestCase, SubclassTestCase, TestEmpty, TestBig,
TestReversed)

View File

@ -230,11 +230,22 @@ reversed_next(reversedobject *ro)
return item;
}
static PyObject *
reversed_reverse(reversedobject *ro, PyObject *unused)
{
return PyObject_GetIter(ro->seq);
}
PyDoc_STRVAR(reversed_doc,
"reverse(sequence) -> reverse iterator over values of the sequence\n"
"\n"
"Return a reverse iterator");
static PyMethodDef reversed_methods[] = {
{"__reversed__", (PyCFunction)reversed_reverse,
METH_NOARGS, reversed_doc},
};
PyTypeObject PyReversed_Type = {
PyObject_HEAD_INIT(&PyType_Type)
0, /* ob_size */
@ -266,7 +277,7 @@ PyTypeObject PyReversed_Type = {
0, /* tp_weaklistoffset */
PyObject_SelfIter, /* tp_iter */
(iternextfunc)reversed_next, /* tp_iternext */
0, /* tp_methods */
reversed_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */