Generators: functions that pause
A function with yield in it can hand back a value, stop, and later carry on from the same line with its variables intact. Here is where its frame goes in between, drawn one next at a time.
01 A function that stops halfway
This function has no return. Calling it seems to do nothing, and each next gets one more number out of it.
Between the first and second next, the function is not running. Yet it remembers that i was 0 and that it was sitting on line 4. Where does that state live?
02 The usual picture: a frame dies on return
An ordinary call pushes a frame holding its arguments and locals onto the call stack. When the function returns, the frame is popped and its locals are gone. Call it again and you get a brand new frame that starts at the top.
If generators worked like that, i could not survive between two next calls. So they must keep the frame somewhere other than the stack.
def count_up(n):result = []i = 0while i < n:result.append(i)i += 1return result# runs to the end at once;# its frame is freed on return
def count_up(n):i = 0while i < n:yield ii += 1# runs up to each yield;# its frame waits in between
03 yield sets the frame aside
When the compiler sees yield in a function body, it marks the code as a generator. Calling that function then builds a generator object around a new frame instead of running anything. Each next puts that frame on the stack, runs it to the next yield, and takes it off again without freeing it.
Follow count.py. The stack panel shows frames above the script’s own <module> frame, which stays at the bottom throughout.
- just changed
- running
- thrown away
Line 7 is about to run. The script’s own <module> frame is running underneath and is not drawn. No generator exists yet.
So yield does two things at once: it hands a value to whoever called next, and it parks the frame with its locals and its position. next is the reverse: it puts the parked frame back on the stack and lets it run.
In CPython 3.11 and later, the frame’s data is stored inside the generator object itself. Resuming does not copy anything back: the interpreter links that frame into the thread’s chain of running frames, and unlinks it at the next yield.
04 Peek at the parked frame
A generator exposes its frame as gi_frame, and inspect can tell you which state it is in.
This is a real run on CPython 3.14. Before the first next, the frame already holds n but not i. While suspended it holds both and sits on line 6, the yield. list(gen) resumes it one last time; the loop ends, nothing more is produced, and gi_frame becomes None.
05 One value at a time
Because a generator only works when asked, it never needs to hold all its values at once. A list comprehension builds every element before you use one; a generator expression builds one per next.
getsizeof does not even count the int objects they point to.Figures from CPython 3.14 on a 64-bit Mac. A for loop is the main consumer of generators, and it is just next in a loop that stops at StopIteration:
for x in count_up(2):print(x)
it = iter(count_up(2))while True:try:x = next(it)except StopIteration:breakprint(x)
06 yield is an expression: send and return
yield also receives. gen.send(v) resumes the frame like next does, but the paused yield expression evaluates to v. (next(gen) is the same as gen.send(None).) A return inside a generator ends it, and the returned value rides along on the StopIteration.
The first next is needed because a new generator has not reached a yield yet, so there is nothing to receive a value. Sending a non-None value to a just-created generator raises TypeError.
07 When it bites
Calling a generator function runs none of its body. Checks at the top, like opening a file or validating an argument, only happen on the first next, so the error shows up wherever the generator is first used, not where it was called.
evens = (n for n in range(6) if n % 2 == 0)
list(evens) # [0, 2, 4]
list(evens) # []A generator runs onceAfter it finishes, every further next raises StopIteration straight away, so a second loop sees nothing. Call the function again for a fresh one, or store the values in a list.len(gen)
gen[0]No length, no indexingThe values do not exist until they are produced. Both raise TypeError. Use list(gen) if you really need them all.for line in lines():
breakfinally runs when the generator is closedLeaving the loop early leaves the frame parked. Its finally block runs when the generator is closed or garbage-collected. CPython’s reference counting usually does that at once; other interpreters may do it much later. Use with around the source, or call gen.close().next again.