Skip to content

Generators: functions that pause

Working knowledgeUnder the hood

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.

count.py
def count_up(n):
i = 0
while i < n:
yield i
i += 1
gen = count_up(2)
print(next(gen))
print(next(gen))
print(next(gen))
Shell
$ python3 count.py
0
1
Traceback (most recent call last):
File "count.py", line 10, in <module>
print(next(gen))
~~~~^^^^^
StopIteration

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.

return
def count_up(n):
result = []
i = 0
while i < n:
result.append(i)
i += 1
return result
# runs to the end at once;
# its frame is freed on return
yield
def count_up(n):
i = 0
while i < n:
yield i
i += 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.

Three calls to next(gen)
Step 1 of 8
Line 7
Call stack · above <module>
Empty
gen’s frame, kept by the generator
Empty
Printed
Empty
  • 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.

— state

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.

peek.py
import inspect
def count_up(n):
i = 0
while i < n:
yield i
i += 1
gen = count_up(2)
print(inspect.getgeneratorstate(gen), gen.gi_frame.f_locals)
print(next(gen))
print(inspect.getgeneratorstate(gen), gen.gi_frame.f_locals,
"line", gen.gi_frame.f_lineno)
print(next(gen))
print(list(gen))
print(inspect.getgeneratorstate(gen), gen.gi_frame)
Shell
$ python3 peek.py
GEN_CREATED {'n': 2}
0
GEN_SUSPENDED {'n': 2, 'i': 0} line 6
1
[]
GEN_CLOSED None

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.

size.py
import sys
squares_list = [x * x for x in range(1_000_000)]
squares_gen = (x * x for x in range(1_000_000))
print(sys.getsizeof(squares_list))
print(sys.getsizeof(squares_gen))
Shell
$ python3 size.py
8448728
208
ListAbout 8 MBA million pointers, before you read the first one. getsizeof does not even count the int objects they point to.
Generator208 bytesOne parked frame. Its size does not depend on how many values it will produce.

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 loop
for x in count_up(2):
print(x)
what it does
it = iter(count_up(2))
while True:
try:
x = next(it)
except StopIteration:
break
print(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.

total.py
def running_total():
total = 0
while True:
x = yield total
if x is None:
return total
total += x
acc = running_total()
print(next(acc)) # run to the first yield
print(acc.send(5))
print(acc.send(3))
try:
acc.send(None)
except StopIteration as e:
print("finished with", e.value)
Shell
$ python3 total.py
0
5
8
finished with 8

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().
A parked frame keeps its locals aliveA suspended generator holds every local in its frame. If one of them is a large buffer, it stays in memory as long as the generator does, even if you never call next again.

08 Check yourself

Question

After g = count_up(3), how much of count_up’s body has run?

Question

Between two next calls, where is the generator’s frame?

Question

A generator yields 1, 2, 3. You loop over it twice. What does the second loop print?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?