What makes an iterator an iterator?

Alex Martelli aleax at mac.com
Thu Apr 19 23:00:31 EDT 2007


7stud <bbxx789_05ss at yahoo.com> wrote:
   ...
> > repeatedly calls....[type(_t).next(t)]
> 
>  As far as I can tell, if the call was actually _t.next(), the code I
> asked about would work.  However, the name look up for 'next' when you

All of your following lamentations are predicated on this assumption, it
would seem.  Very well, let's put it to the text, as Python makes it so
easy..:

>>> class sic: pass
... 
>>> _t = sic()
>>> def nexter(): 
...   yield 23
... 
>>> _t.next = nexter
>>> for i in range(10):
...   print _t.next()
... 
<generator object at 0x7c080>
<generator object at 0x7c080>
<generator object at 0x7c080>
<generator object at 0x7c080>
<generator object at 0x7c080>
<generator object at 0x7c080>
<generator object at 0x7c080>
<generator object at 0x7c080>
<generator object at 0x7c080>
<generator object at 0x7c080>

See?  a loop that calls _t.next() and only terminates when that raises
StopIteration will never exit when _t.next is a generator function (as
opposed to *the result of calling* a generator function, which is an
*iterator object*).  This applies when _t.next is looked up on the
instance, as we ensured we were in this toy example, just as much as
when it's coming from type(_t) -- which is why in this context the
distinction is pedantic, and why it was definitely not crucial, as you
appear (on the basis of this false idea you have) to think it was, in
the Nutshell (where I went for readability rather than pedantic
precision in this instance).

If you want to implement a class whose next method internally uses a
generator, that's pretty easy, e.g.:

class sane(object):
    def __init__(self, sentence='four scores and twenty years ago'):
        def agenerator():
            for word in sentence.split(): yield word
        self._thegen = agenerator()
    def __iter__(self): return self
    def next(self): return self._thegen.next()

there -- easy, innit?  You just have to understand the difference
between calling a generator function, and calling the next method of the
object (iterator) which is returned by that function when called:-).


Alex



More information about the Python-list mailing list