[Python-Dev] Re: PEP 322: Reverse Iteration (original) (raw)

Phillip J. Eby pje at telecommunity.com
Wed Nov 5 12:06:13 EST 2003


At 05:34 PM 11/5/03 +0100, Samuele Pedroni wrote:

At 17:09 05.11.2003 +0100, Alex Martelli wrote:

On Wednesday 05 November 2003 03:54 pm, Phillip J. Eby wrote: ... > >reverse iteration. The iterator object has no way of knowing in advance > >that it is going to be called by reversed(). > > Why not change enumerate() to return an iterable, rather than an > iterator? Then its reversed method could attempt to delegate to the > underlying iterable. Is it likely that anyone relies on enumerate() being > an iterator, rather than an iterable? I think he was wondering whether people rely on

enumerate([1,2]).next i = enumerate([1,2]) i is iter(i) working , vs. needing iter(enumerate([1,2]).next

Yes, precisely.

I think he was proposing to implement enumerate as

class enumerate(object): def init(self,iterable): self.iterable = iterable def iter(self): i = 0 for x in self.iterable: yield i,x i += 1 def reversed(self): rev = reversed(self.iterable) try: i = len(self.iterable)-1 except (TypeError,AttributeError): i = -1 for x in rev: yield i,x i -= 1

Yes, except I hadn't thought it out in quite that much detail. Thanks for the clarification.



More information about the Python-Dev mailing list