Python Reference ยท Exceptions
Python StopIteration and StopAsyncIteration
Reference for Python StopIteration and StopAsyncIteration: how iterators signal the end, next() defaults, the value attribute and the generator RuntimeError rule.
StopIteration is how an iterator says "I have nothing more to give". When you call next() on an exhausted iterator, it raises StopIteration. A for loop calls next() for you and treats this exception as the signal to end quietly, so you normally never see it.
StopAsyncIteration is the same idea for asynchronous iterators: the __anext__() awaitable raises it, and async for stops cleanly. Both inherit directly from Exception.
it = iter([1, 2]) next(it) # 1 next(it) # 2 next(it) # StopIteration
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
try: value = next(iterator) except StopIteration as stop: result = stop.value # generator's return value, or None value = next(iterator, default) # no exception
| Name | Description |
|---|---|
value |
On StopIteration: the value returned by a generator (return x), or the first argument given to the exception; None by default. |
Raises when: next() is called on an exhausted iterator; __next__() signals the end; __anext__() raises StopAsyncIteration for async iterators.
Usage notes
- Prefer
forloops. They handle the end for you. Usenext(it, default)when you want one item or a fallback instead of an exception. - Iterables versus iterators. A list is iterable but not an iterator, so
next([1, 2])raisesTypeError. Calliter()first. - Exhausted means exhausted. Once an iterator raised
StopIteration, it should keep raising it. Generators and file objects cannot be restarted; create a new one. - Generators:
return valueends a generator, and the value travels inStopIteration.value.yield fromhands that value to the outer generator. - PEP 479 rule. If a
StopIterationis raised inside a generator body and not caught, Python turns it intoRuntimeError: generator raised StopIteration. End a generator withreturninstead ofraise StopIteration. - Same for coroutines and async generators: a stray
StopIterationbecomesRuntimeError, andStopAsyncIterationraised in an async generator does too. - Writing
__next__: raiseStopIterationwith no arguments when finished. Do not use it to report errors. - First match idiom.
next(x for x in items if condition(x))raisesStopIterationwhen nothing matches; pass a default to avoid that. - Don't catch it casually. A bare
except Exceptionswallows it and can hide a loop that ended early.
Related
next(),iter(), iterators and generatorsyield,RuntimeError- Lessons: Iterators, Generators