Reading preferences
Concept

Iterators, Generators, and Resource Lifetimes

Trace lazy values and cleanup when an iterator or context is finished.

python, iterators, generators, context managers, yield

Produce values on demand

An iterable can provide an iterator. An iterator supplies values one at a time through next, then raises StopIteration. A generator function is a convenient way to create an iterator: each yield suspends its state.

Python illustration

def counts():
    print("start")
    yield 1
    print("resume")
    yield 2

items = counts()
print(next(items))
print(next(items))
print(list(items))

Prepared output — not live execution:

start
1
resume
2
[]

Calling counts() creates a generator; its body begins at the first next. After the second value it resumes once more when list(items) asks for another value, reaches the end, and is exhausted.

See the reasoning

Watch a generator suspend and resume

Track the generator frame as the caller requests values. This is a prepared demonstration, not live code execution.

Create the generator

Generator frame and caller
  1. Calleritems = counts()Current focus
  2. Generator framenot yet started
  3. Outputnone

Calling counts creates the generator without running its body.

Resource boundaries

Generator expressions also compute values lazily. Iterators can be consumed only once, and laziness does not by itself guarantee low memory use if all results are collected. A generator can contain try/finally; closing it runs pending cleanup. Do not rely on garbage collection to close resources promptly.

contextlib.contextmanager makes a context manager from a generator that yields exactly once. ExitStack can enter a variable number of contexts and unwind them in reverse order, even when a later operation raises. For an async generator, contextlib.aclosing provides deterministic async cleanup. Use explicit resource lifetimes rather than silently suppressing exceptions.

from contextlib import ExitStack
from io import StringIO

with ExitStack() as stack:
    streams = [stack.enter_context(StringIO(text)) for text in ("A", "B")]
    print([stream.read() for stream in streams])
print([stream.closed for stream in streams])

The prepared output is ['A', 'B'] and then [True, True] on separate lines. ExitStack closes the two streams in reverse entry order on exit.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What signals that an iterator is exhausted?
2. What does yield do in a generator function?
3. Can an exhausted generator normally be iterated again from the beginning?
4. What does contextlib.ExitStack help manage?

References and further reading