iterator.next() confusion

Clark C. Evans cce at clarkevans.com
Thu May 29 13:42:51 EDT 2003


Hello all.  The iterator PEP doesn't seem to say if the next() method
of the iterator could be cached during a loop, for example:

    def printall( iterable ):
        next = iter( iterable ).next
        try:
            while 1:
                print next()
        except StopIteration: 
            pass

Code like the above seems to work with most iterables, however,
it will get into an endless loop with the following iterator:

    class evilIterator:
        def __init__(self):
            self.next = self._next_one
        def __iter__(self):
            return self
        def _next_one(self):
            self.next = self._next_two
            return "one"
        def _next_two(self):
            self.next = self._next_stop
            return "two"
        def _next_stop(self):
            raise StopIteration

Which, of course, works just fine in:

    def printall( iterable ):
        for itm in iterable:
            print itm

Which is incorrect use of the iterator PEP?  The former or the latter?
If it is the former, why was this done, as it seems storing the function
would save a dictionary lookup on each iteration.  The latter, while a
cute implementation of a state machine, could be done other ways.

Best,

Clark    





More information about the Python-list mailing list