[Python-Dev] PEP 322: Reverse Iteration

Jeremy Fincher fincher.8 at osu.edu
Wed Nov 5 08:33:37 EST 2003

On Tuesday 04 November 2003 08:12 pm, Guido van Rossum wrote:
> In private mail Raymond withdrew the suggestion that enumerate()
> implement __reversed__; I think Raymond won't mind if I quote him here:
> [Raymond]
> > Unfortunately, that idea didn't work out.  The enumerate object does not
> > hold the original iterable; instead, it only has the result of
> > iter(iterable).  Without having the iterable, I don't see a way for it
> > to call iterable.__reversed__.  The essential problem that at creation
> > time, the enumerate object does know that it is going to be called by
> > reversed().

I had always assumed that enumerate.__reversed__ would attempt to call a 
reversed iterator on the sequence.  Since enumerate is only sensibly used on 
sequences (which are guaranteed to provide a reverse iterator) it could never 
fail in sensible cases (unless there's some usage of enumerate on 
non-sequences that I'm missing).

> I'm not sure I even like the idea of reversed() looking for a
> __reversed__ method at all.  I like the original intention best:
> reversed() is for reverse iteration over *sequences*.  (See the first
> paragraph of the section "Rejected Alternatives" in the PEP.)

I think the search for the __reversed__ method is the meat of the proposal; I 
can define for myself a simple two-line generator that iterates in reverse 
over sequences.  What I need the language to define for me is a protocol for 
iterating over objects in reverse and for providing users of my own classes 
with the ability to iterate over them in reverse in a standard way.

If this proposal could be satisfied by the simple definition:

def reversed(seq):
    for i in xrange(len(seq)-1, -1, -1):
        yield seq[i]

I wouldn't be for it.  The reason I'm +1 is because I want a standard protocol 
for iterating in reverse over objects.


More information about the Python-Dev mailing list