Python Glossary Русский

all Python 3Exceptionsexception

StopIteration

built-in exceptions

Signals that an iterator is exhausted. for loops and generators catch it automatically — you rarely need to raise it by hand.

Syntax

raise StopIteration

The big trap is PEP 479: if StopIteration escapes the body of a generator (for example from an unguarded inner next() call), Python turns it into RuntimeError instead of quietly ending the generator — finish a generator with a plain return. It also inherits from Exception, so a broad except Exception silently eats the end-of-iteration signal along with real errors. When running out of items is expected, prefer next(it, default) over try/except.

Examples

it = iter([1, 2])
next(it)  # 1
next(it)  # 2
next(it)  # StopIteration
# В генераторе завершайте через return: raise StopIteration здесь даёт RuntimeError (PEP 479)
def gen():
    yield 1
    return  # автоматически поднимает StopIteration

See also

Open in the full glossarydocs.python.orgReport an inaccuracy