Skip to content Skip to sidebar Skip to footer

Python: Next() Is Not Recognized

When I do next(ByteIter, '')<<8 in python, I got a name error saying 'global name 'next' is not defined' I'm guessing this function is not recognized because of python vers

Solution 1:

From the docs

next(iterator[, default])

Retrieve the next item from the iterator by calling its next() method. 
If default is given, it is returned if the iterator is
exhausted, otherwise StopIteration is raised.

New in version 2.6.

So yes, it does require version 2.6.


Solution 2:

though you could call ByteIter.next() in 2.6. This is not recommended however, as the method has been renamed in python 3 to next().


Solution 3:

The next() function wasn't added until Python 2.6.

There is a workaround, however. You can call .next() on Python 2 iterables:

try:
    ByteIter.next() << 8
except StopIteration:
    pass

.next() throws a StopIteration and you cannot specify a default, so you need to catch StopIteration explicitly.

You can wrap that in your own function:

_sentinel = object()
def next(iterable, default=_sentinel):
    try:
        return iterable.next()
    except StopIteration:
        if default is _sentinel:
            raise
        return default

This works just like the Python 2.6 version:

>>> next(iter([]), 'stopped')
'stopped'
>>> next(iter([]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in next
StopIteration

Post a Comment for "Python: Next() Is Not Recognized"