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

Raymond Hettinger python at rcn.com
Wed Nov 5 15:54:22 EST 2003


[GvR]
> I'm okay with adding reversed() as a builtin that works for sequences
> only but I'm not okay with adding the __reversed__ protocol.
> 
> For me, the main advantage of reversed() is that it expresses better
> what I mean when I'm going over a list (or other concrete sequence)
> backwards.  The __reversed__ protocol muddles the issue by inviting to
> try to make reversed() work for some iterators; I don't see the use
> case (or if I do see it, I see it as much less important than the
> previous one).

I'm not married to the idea of __reversed__ but think it should probably
be kept (if my intuition is off on this one, we can pull it out before
the beta release).

On the plus side:

* Many of the original posters either specifically requested this or
included some variation of it in their proposals.

* There is a small group (including Jeremy Fincher) that consider a
reversal protocol to be essential.

* It is particularly useful for xrange() because it reduces the overhead
to zero without touching the API.  The implementation patch on SF shows
that this can be done cleanly.  Essentially, __reverse__ forwards the
call to __iter__ with the arguments rearranged for reverse order.

* It leaves open the possibility that someone could add __reverse__ to
file objects, enabling them loop in reverse (helpful in reviewing log
files for example).

* There is a small group that passionately wants reverse() to work with
enumerate() and Alex appears to be close to figuring out how to overcome
the implementation challenges.

* The iter/__iter__ pair neatly parallels reversed/__reversed__.

* It is pythonic to put hooks in for just about everything.  Sooner or
later, someone needs the hook.  For everyone else, it's invisible.


On the minus side:

* I think you got cold feet when some poster presented a wacky or
misguided use for it.  There's no avoiding that; even Alex's dirt simple
__copy__ protocol can be turned into an atrocity by someone so inclined.



>  About your last bullet, I wonder if one of the
> issues is that when doing a forward loop over a container, we don't
> really care that much about the order as long as we get all items
> (witness the popularity of looping over dicts).  But when doing a
> reverse loop, we clearly *do* care about the order.  So forward and
> reverse iteration are not symmetric.  This may explains why 3 out of 5
> examples you found *need* the index.

Incisive analysis.



are-your-feet-feeling-warmer-now-ly yours,


Raymond Hettinger




More information about the Python-Dev mailing list