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 iteratorby calling its next() method. Ifdefaultis given, it is returned if the iteratoris exhausted, otherwise StopIteration is raised. Newin 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() << 8except 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()
defnext(iterable, default=_sentinel):
try:
return iterable.next()
except StopIteration:
if default is _sentinel:
raisereturn 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, innext
StopIteration
Post a Comment for "Python: Next() Is Not Recognized"