What makes an iterator an iterator?

I V ivlenin at gmail.com
Wed Apr 18 02:13:39 EDT 2007


On Wed, 18 Apr 2007 15:39:22 +1000, Steven D'Aprano wrote:
> I thought that an iterator was any object that follows the iterator
> protocol, that is, it has a next() method and an __iter__() method.
...
> class Parrot(object):
...
>     def __init__(self):
>         self.next = self._next()

self.next isn't a method here, it's a generator. You could do:

    def __init__(self):
          self.next = self._next().next

But, having tested, that doesn't appear to work either - I think
this is because, again, self.next is not strictly a method, it's an
attribute that happens to be callable.

The python manual gives you a possible solution:

---QUOTE http://docs.python.org/lib/typeiter.html ---
Python's generators provide a convenient way to implement the iterator
protocol. If a container object's __iter__() method is implemented as a
generator, it will automatically return an iterator object (technically, a
generator object) supplying the __iter__() and next() methods.
---END QUOTE---

i.e., just rename your _next function to __iter__ . Your class won't
itself be an iterator, but it will be usable in for statements and so one,
and convertable to an iterator with the iter builtin.



More information about the Python-list mailing list