pythonpython-2.5

def next() for Python pre-2.6? (instead of object.next method)


Python 2.6+ and 3.* have next(), but pre-2.6 only offers the object.next method. Is there a way to get the next() style in pre-2.6; some "def next():" construction perhaps?


Solution

  • class Throw(object): pass
    throw = Throw() # easy sentinel hack
    def next(iterator, default=throw):
      """next(iterator[, default])
    
      Return the next item from the iterator. If default is given
      and the iterator is exhausted, it is returned instead of
      raising StopIteration.
      """
      try:
        iternext = iterator.next.__call__
        # this way an AttributeError while executing next() isn't hidden
        # (2.6 does this too)
      except AttributeError:
        raise TypeError("%s object is not an iterator" % type(iterator).__name__)
      try:
        return iternext()
      except StopIteration:
        if default is throw:
          raise
        return default
    

    (throw = object() works too, but this generates better docs when inspecting, e.g. help(next). None is not suitable, because you must treat next(it) and next(it, None) differently.)