Lesson · Iteration Protocol
Generators
76 min readGenerators
Generators are iterators implemented with suspended function execution. `yield` preserves local state between values, which makes generators ideal for pipelines, traversal, and incremental processing.
Learning goals
- Trace what happens when
read_chunks("ABCDEFGHI", 3)is called versus when its first chunk is requested. - Explain how
yieldsuspends a frame and which local state survives between chunks. - Predict the output when the chunk size does not divide the input evenly, for example size 4 over 9 characters.
- Use
yield fromto delegate to an inner iterable and explain what it forwards beyond values. - Explain the three control methods (
send,throw,close) and when each is the right tool.
Mental model
Calling a generator function freezes the body at the entrance: you get a generator object and nothing has executed. Each request advances the frame until it reaches a yield, which hands one value out and suspends the frame exactly there; the next request resumes on the following line with every local variable intact. The flow ends when the function returns, which surfaces as StopIteration to the iterator protocol.
A generator is a paused function
call, resume, yield, suspend, close
Mental model
the same mechanism as a compact list
generator call → generator object next()/send() → run → yield → suspend → resume
Core idea
A generator function looks like an ordinary function but runs under a different contract: calling it produces a generator object, and the body executes in slices, one yield at a time, with the frame and locals preserved between slices. That suspension is the mechanism behind small-memory pipelines, incremental traversal, and the control methods .send(), .throw(), and .close(). Reading a generator means tracking two things at once: the value that came out and the line the frame is parked on.
yield
yield produces one value and suspends the generator frame instead of returning permanently. The next iteration resumes execution after the yield point.
Generator functions
A function containing yield returns a generator object when called instead of executing the body to completion immediately. Execution begins on the first iteration request.
Suspension and resumption
At yield, Python preserves the generator frame and returns a value to the caller. A later next() resumes from the instruction after that yield with the same local state.
Generator state
A generator preserves its frame, local variables, and instruction position while suspended. This is why it can resume exactly after the previous yield.
Lazy pipelines
A lazy pipeline composes iterators so each item moves through stages only when demanded by the final consumer. It can process very large inputs with small working memory.
yield from
yield from delegates iteration to another iterable or generator and also forwards generator protocol operations. It simplifies nested generator pipelines.
.send()
generator.send(value) resumes a suspended generator and makes yield evaluate to the supplied value. The first send to a just-created generator must supply None unless the generator is advanced first.
.throw()
generator.throw(exc) raises an exception at the generator's suspension point. Generator code can handle it with normal exception logic or allow it to propagate.
.close()
generator.close() requests termination by injecting GeneratorExit at the suspension point. Cleanup in finally blocks can run as the generator closes.
Walkthrough
def read_chunks(data, size)contains ayield, so calling it slices nothing; it returns a generator object parked before the loop.- The
forloop pulls the first chunk: the frame runsrange(0, 9, 3), takesstart = 0, yieldsdata[0:3], which is"ABC", and suspends before the next loop turn. - The second and third requests resume with
start = 3andstart = 6, yielding"DEF"and"GHI"; a fourth request finds therangeexhausted and raisesStopIteration, which ends theforloop quietly. - Predict before running: the number of
printlines, the exact chunk strings, and the value ofstartwhile each chunk is produced.
Experiments to try
- Run
read_chunks("ABCDEFGHI", 4)and predict the chunks first; the last one is shorter becausedata[8:12]stops at the end of the string. - Call the function without iterating it and inspect the result with
type(); add aprintas the loop's first statement and note that it appears only when values are requested. - Advance the generator with
next(chunks)twice, then hand it to aforloop and observe that the loop continues from the third chunk instead of restarting. - Wrap the generator in a two-stage pipeline with a second stage that filters short chunks, and record how many items each stage processes.
Playable lesson
Lab: Generator execution pointer
Highlight the active source line, generator locals, yielded values, and suspended/running/closed states.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Generator execution pointer
Source
State
createdFrame locals (survive suspension)
- data = 'ABCDEFGHI'
- size = 3
Yielded
Predict first
How many lines of `read_chunks` run when you call it without iterating?
Calling a generator function runs zero lines. It binds the parameters and returns a generator object parked before the body; the first request for a value is what starts the code.
Press Next (or Play) to issue the first request and start the body.
Common mistakes
- Expecting a generator to restart: once the frame has returned, every later
next()raisesStopIteration, so a secondforloop over the same object produces nothing. - Assuming the body runs when the function is called: calling a generator function executes zero lines, so setup code placed inside it is deferred until the first request for a value.
- Leaking references through the suspended frame: a paused generator keeps everything its locals reference alive, so a long-lived pipeline can hold a large source object even when the consumer stops asking.
- Calling
.send(value)before the generator has started:yieldhas not executed yet, so there is no paused expression to receive the value and Python raisesTypeError; advance once withnext()or sendNonefirst.
Practice: Easy
- Type the worked example into a file and record the three printed chunks; then print
type(read_chunks)andtype(read_chunks("ABCDEFGHI", 3))and state which object is callable. - Change the size to 4 and write the expected chunk list before running; explain where the shorter final chunk comes from.
- Add
print("started")as the first line of the generator body and observe that the message does not appear until the firstnext()call.
Practice: Medium
- Advance a generator twice with
next()and then complete it with aforloop; list the chunks the loop sees and explain why it does not repeat the first two. - Write
counter(n)that counts from 1 tonwithyield; drive it withnextuntilStopIterationappears and catch the exception explicitly. - Use
yield fromto flatten two nested lists into one stream; compare that version against a doubly nestedforloop with plainyield.
Practice: Hard
- Build a three-stage pipeline of generator functions and feed it 1,000 items; count how many items each stage processes and explain where laziness changes the totals.
- Write a generator with a
try/finallythat records cleanup, close it early with.close(), and verify thefinallyblock runs; describe whatGeneratorExitdid to the frame. - Give a generator a two-way interface with
.send(): an accumulator whoseyieldexpressions receive new numbers; document the required first step and one failure mode when the caller forgets it.
Lesson checklist
- I can say what calling a generator function does before any value is requested.
- I can trace a suspended frame through two
yieldpoints and name the line where it resumes. - I can predict the final chunk when the size does not divide the input evenly.
- I can explain how
.send(),.throw(), and.close()interact with a suspended frame.
Remember
A generator function is a function that runs in installments: calling it builds a generator object, and each request executes up to the next `yield`, hands out one value, and parks the frame with its locals intact. That single mechanism provides lazy pipelines, incremental traversal, and the two-way control methods `.send()`, `.throw()`, and `.close()`. Design around two facts: nothing runs before the first request, and once the function returns, the same generator never produces again.
Interview angles
What is the main purpose of **yield**?+
yield produces one value and suspends the generator frame instead of returning permanently. The next iteration resumes execution after the yield point.
What should you pay attention to when using **Generator functions**?+
A function containing yield returns a generator object when called instead of executing the body to completion immediately. Execution begins on the first iteration request.
How does **Suspension and resumption** fit into this lesson?+
At yield, Python preserves the generator frame and returns a value to the caller. A later next() resumes from the instruction after that yield with the same local state.
What happens when you call `.send(5)` on a generator that has been created but never advanced, and why?+
The frame is parked at the function entrance, before any yield has executed, so there is no paused yield expression to receive the value and Python raises TypeError. Advance it once with next() (or send None) before sending real values.