[Python-Dev] __reversed__ protocol

Raymond Hettinger raymond.hettinger at verizon.net
Tue Nov 18 16:50:17 EST 2003

At one point, PEP 322 had proposed checking to see if an object defined
__reversed__ and if not available, then proceeding normally using
__getitem__ and __len__.  While the idea had supporters, it got taken
out because Guido worried that it would be abused by being applied to
general iterables like generators and objects returned by itertools.

So, an improved version of the idea is to check for __reversed__ but
only use it when the object also defines __len__.  That precludes the
abuses but leaves the protocol open for the normal use cases.  The
simple patch is listed below.

Guido doesn't have time for this now and asked me to present it to you
guys.  What do you guys think?


diff -c -r1.10 enumobject.c
*** enumobject.c        7 Nov 2003 15:38:08 -0000       1.10
--- enumobject.c        18 Nov 2003 21:39:51 -0000
*** 174,181 ****
        if (!PyArg_UnpackTuple(args, "reversed", 1, 1, &seq))
                return NULL;

!       /* Special case optimization for xrange and lists */
!       if (PyRange_Check(seq) || PyList_Check(seq))
                return PyObject_CallMethod(seq, "__reversed__", NULL);

        if (!PySequence_Check(seq)) {
--- 174,181 ----
        if (!PyArg_UnpackTuple(args, "reversed", 1, 1, &seq))
                return NULL;

!       if (PyObject_HasAttrString(seq, "__reversed__") &&
!           PyObject_HasAttrString(seq, "__len__"))
                return PyObject_CallMethod(seq, "__reversed__", NULL);

        if (!PySequence_Check(seq)) {

More information about the Python-Dev mailing list