Has Next in Python Iterators

Hrvoje Niksic hniksic at xemacs.org
Mon Oct 25 16:11:26 CEST 2010

Kelson Zawack <zawackkfb at gis.a-star.edu.sg> writes:

> Iterators however are a different beast, they are returned by the
> thing they are iterating over and thus any special cases can be
> covered by writing a specific implementation for the iterable in
> question.  This sort of functionality is possible to implement,
> because java does it.

Note that you can wrap any iterator into a wrapper that implements
has_next along with the usual iteration protocol.  For example:

class IterHasNext(object):
    def __init__(self, it):
        self.it = iter(it)

    def __iter__(self):
        return self

    def next(self):
        if hasattr(self, 'cached_next'):
            val = self.cached_next
            del self.cached_next
            return val
        return self.it.next()

    def has_next(self):
        if hasattr(self, 'cached_next'):
            return True
            self.cached_next = self.it.next()
            return True
        except StopIteration:
            return False

>>> it = IterHasNext([1, 2, 3])
>>> it.next()
>>> it.has_next()
>>> it.next()
>>> it.next()
>>> it.has_next()
>>> it.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 11, in next

More information about the Python-list mailing list