Def next () for Python pre-2.6? (instead of the 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 following () style in pre-2.6; some "def next ():" perhaps building?

+5
source share
3 answers
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 it creates better documents when checking, for example help(next). NoneIs not suitable, because you have to treat next(it)and next(it, None)different.)

+11
source

R. Pat seems to have a good answer. One additional call to add: if you are writing code to run on different versions of Python, you can conditionally define a definition:

try:
    next = next
except NameError:
    def next():
        # blah blah etc

, next, , , .

next = next, , :

from backward import next
+6

Simplified Method:

import operator

next = operator.methodcaller("next")

Ned's suggestion of placing it in a block tryalso works here, but if you are going to follow this route, one minor note: in Python 3, calling next()on a non-iterator calls a TypeError, while this version will raise AttributeError.

Edit: Nothing. As Steveha points out, it operator.methodcaller()was introduced only in 2.6, which is a shame.

+2
source

All Articles