[Python-Dev] PEP 322: Reverse Iteration

Guido van Rossum guido at python.org
Tue Nov 4 20:12:39 EST 2003

> >Ah, so it is.  Then the PEP's abstract is wrong:
> >
> >"""
> >This proposal is to add a builtin function to support reverse
> >iteration over sequences.
> >"""
> >
> >Also, the PEP should enumerate (:-) which built-in types should be
> >modified in this way, to give an impression of the enormity (or not)
> >of the task.

> what is not clear to me is that the PEP is explicit about reversed() 
> refusing general iterables and in particular infinite iterators, but then 
> the combination reversed enumerate.__reversed__ would accept them or not?. 
> Will enumerate implement __reversed__ in terms of keeping the enumerate 
> argument around instead of just a iterator derived from it and reproducing 
> then the reversed behavior: limits checks and implementation strategy on 
> the original argument if/when __reversed__ is called?
> so
> for x in reversed(enumerate(itertools.count())):
>    pass
> would throw an exception instead of not terminating, OTHERWISE with
> the strategy of consuming the iterator if x is a finite iterator but
> without __len__ then
> reversed(x) would not work but
> reversed(enumerate(x)) would.
> Further enumerate.__iter__ does not enable re-iteration, simply it
> does not return a fresh iterator but what about
> enumerate.__reversed__ ?

In private mail Raymond withdrew the suggestion that enumerate()
implement __reversed__; I think Raymond won't mind if I quote him here:

> 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().
> No other sequence object has to have a __reversed__ method.  Like its
> cousin, __iter__, some objects may be a performance boost from a custom
> iterator but none of them have to have it.

So we're back to square one: reversed(enumerate(X)) won't work, even
if reversed(X) works.

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.)

Anyway, as Raymond predicted, the discussion is being distracted by
side issues.

I personally like the idea better of having a variant of xrange() that
generates a numerical sequence backwards better.  Or perhaps we should
just get used to recognizing that [x]range(n-1, -1, -1) iterates over
range(n) backwards...

--Guido van Rossum (home page: http://www.python.org/~guido/)

More information about the Python-Dev mailing list