[Python-Dev] Re: PEP 322: Reverse Iteration

Raymond Hettinger python at rcn.com
Wed Nov 5 07:29:17 EST 2003

> Raymond is proposing (in the PEP) a custom reverse via a __reversed__
> special method.

That was requested by a number of contributors on comp.lang.python.
It's purpose is to allow user's to add reverse iteration support to
objects that otherwise only offer forward iteration but not sequence

The custom reversed method is not an essential part of the proposal.
It's just a hook for someone who might need it.

> I'm assuming that irange() [and enumerate(), and possibly
> others] would need such a method, in order to cover just this case.

Not really.  When you go to write the code, it becomes clear that it
doesn't apply to enumerate or the other itertools.  The issue is that
the iterator object holds only the result of iter(iterable) and is in no
position to re-probe the underlying iterable to see if it supports
reverse iteration.  The iterator object has no way of knowing in advance
that it is going to be called by reversed().

So, I'm not proposing to add __reversed__ to any existing python
objects.  It may make sense for xrange, but that is an efficiency issue
not an API issue (xrange already works with reversed() without adding a
custom method).


More information about the Python-Dev mailing list