Iterator - what I am missing

Steven Taschuk staschuk at telusplanet.net
Thu Aug 14 23:51:35 CEST 2003


Quoth Helmut Jarausch:
> I cannot find out what I miss with my iterator example.
> 
> I have a linked list class Queue which has a 'Head' attribute
> and the following
> 
>      def __iter__(self):
>          if  self.Head == None: raise StopIteration
>          return self.Head

This method should return an iterator, not a node.  A for loop
calls .next() on the same object -- the iterator object -- at each
iteration; that method is supposed to return successive values on
each call.  It's as if

    for x in iterable:
        mung(x)

were

    iterator = iter(iterable)  # get iterator object
    try:
        while True:
            x = iterator.next()  # call its .next() method repeatedly
            mung(x)
    except StopIteration:
        pass

If you walk through this blurb using an instance of your Queue
class for the 'iterable' variable, you'll quickly see how the
infinite loop occurs.  If you walk through it using

    class Queue(object):
        # ...
        def __iter__(self):
            return QueueIterator(self.Head)

    class QueueIterator(object):
        def __init__(self, firstnode):
            self.nextnode = firstnode
        def __iter__(self):
            return self
        def next(self):
            if self.nextnode is None:
                raise StopIteration()
            node = self.nextnode
            self.nextnode = self.nextnode.NNd
            return node

instead, you'll see how what's supposed to happen.

In your actual code you'll probably not want to use an explicit
QueueIterator class; a generator function, with its implicit
iterator object, is simpler here:

    from __future__ import generators  # needed in Python 2.2

    class Queue(object):
        # ...
        def __iter__(self):
            node = self.Head
            while node is not None:
                yield node
                node = node.NNd

-- 
Steven Taschuk                                                 o- @
staschuk at telusplanet.net                                      7O   )
                                                               "  (





More information about the Python-list mailing list