Has Next in Python Iterators

Hrvoje Niksic hniksic at xemacs.org
Mon Oct 25 10:11:26 EDT 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
        try:
            self.cached_next = self.it.next()
            return True
        except StopIteration:
            return False

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



More information about the Python-list mailing list