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

Guido van Rossum guido at python.org
Wed Nov 5 17:21:12 EST 2003

> > >The __reversed__ protocol muddles the issue by inviting to
> > > try to make reversed() work for some iterators
> The invitation is to add efficient reverse iteration support to regular
> objects and user defined classes, not for iterators.  Though I won't be
> suprised if someone tries, the only iterator that has a chance with this
> is enumerate, but that is not what the hook is for.

Yeah, but there was widespread misunderstanding here (for a while even
you and Alex were convinced that it was possible for enumerate).

Several functions in itertools could easily be made to support
__reversed__ *if* their argument supports it (or even if not in one

chain(*iterables) -- you can define reversed(chain(*iterables)) as

   for it in reversed(iterables):
       for element in reversed(it):
           yield element

cycle(iterable) -- this one is infinite but reversed(cycle(x)) could be
defined as cycle(reversed(x)).

ifilter(pred, it) -- again, it's easy to define reversed(ifilter(P, X))
as ifilter(P, reversed(X)).  Ditto for ifilterfalse.

imap() -- this would not be so easy because the iterables might not be
of equal length, so you can't map reversed(imap(F, X, Y)) to imap(F,
reversed(X), reversed(Y)).  But for a single sequence, again it could be

islice() -- seems easy enough.

starmap() -- simple, this is like imap() with a single argument.

repeat() -- trivial!  reversed(repeat(X[, N])) == repeat(X[, N]).

dropwhile(), takewhile(), count() aren't amenable.

So, unless you want to open this can of worms, I'd be for a version of
reversed() that does *not* support __reversed__, making it perfectly
clear it only applies to real sequences.

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

More information about the Python-Dev mailing list