next(ByteIter, '')<<8
Pythonで行うと、名前エラーが発生しました
「グローバル名 'next' は定義されていません」
Pythonのバージョンが原因で、この機能が認識されていないと思いますか?私のバージョンは2.5です。
ドキュメントから
next(イテレータ[, デフォルト])
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.
はい、バージョン 2.6 が必要です。
next()
関数は Python 2.6 まで追加されませんでした。
ただし、回避策があります。.next()
Python 2 iterables で呼び出すことができます:
try:
ByteIter.next() << 8
except StopIteration:
pass
.next()
をスローしStopIteration
、デフォルトを指定できないため、StopIteration
明示的にキャッチする必要があります。
それを独自の関数でラップできます。
_sentinel = object()
def next(iterable, default=_sentinel):
try:
return iterable.next()
except StopIteration:
if default is _sentinel:
raise
return default
これは、Python 2.6 バージョンと同じように機能します。
>>> next(iter([]), 'stopped')
'stopped'
>>> next(iter([]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in next
StopIteration