One protocol of two methods — and on it stand loops, comprehensions, unpacking, the with of contextlib and all of async. A generator turns out to be a suspended frame, and yield from not sugar for a loop but a two-way channel.
Commit to an output and a reason before you open the answer.
it = iter([1, 2, 3])
print(list(it))
print(list(it))[1, 2, 3]
[]The second pass over the same object is empty. The list itself is intact.def g():
print("body started")
yield 1
x = g()
print("created")
print(next(x))created
body started
1Calling the function did not execute a single line of its body.def inner():
got = yield 1
print("inner got:", got)
return "result"
def outer():
for v in inner():
yield v
o = outer()
next(o)
o.send("hello")inner got: NoneWe sent “hello”, and what arrived inside was None. And the returned “result” went nowhere.import tracemalloc, sys
# [i*i for i in range(1_000_000)] versus
# (i*i for i in range(1_000_000))
print(sys.getsizeof(i for i in range(10)))200A list of a million squares takes 40.4 MB. A generator expression takes 200 bytes regardless of the number of elements.An iterable can hand out an iterator: it has __iter__.
An iterator can hand out the next element: it has __next__, and it signals the end with the StopIteration exception. It has an __iter__ of its own too, which returns itself.
A generator is a way of getting an iterator from a function. A function with yield is not executed when called; instead it creates an object with a suspended frame: local variables, the position of execution, the value stack.
Snippet A. An iterator keeps its position inside itself; having reached the end, it stays in that state. The second list() honestly asks for the next element and immediately gets StopIteration.
The split into two concepts exists precisely for this. A list is an iterable: on every for it hands out a new iterator, so it can be traversed as many times as you like. The iterator itself is single-use, because it is the position.
Hence the practical point: a function that accepts a “sequence” and walks it twice will break on a generator — silently, with an empty second pass. If a repeated traversal is needed, either materialize it with list() or require exactly a sequence in the contract.
Snippet B. g() creates an object and returns control immediately. The first line of the body runs only on the first next.
This is a trap for argument checks: a raise ValueError at the start of a generator fires not at the moment of the call but when someone begins the traversal — possibly in another function, with a useless traceback. The technique against this is well known: an ordinary function checks the arguments and returns an inner generator.
But the main property comes from the same place: work is done on demand. A generator reading a file will not read a single byte until a line is asked of it.
yield is two-way, and a loop does not pass that onThis is usually where the gap shows. yield is not only “hand a value out” but also a receiving point: the expression x = yield v gets whatever comes from outside through send. A generator can also take an exception in through throw, and return a value through return, which arrives in the StopIteration.value field.
Snippet C shows that an ordinary loop for v in inner(): yield v forwards only values outward. What is sent through send goes to the outer generator and does not go inside; what is returned by return is lost; an exception through throw kills the outer one without letting the inner one clean up.
def outer():
r = yield from inner() # instead of the loop
print("got:", r)
With yield from the same actions give “inner got: hello” and “got: result”. That is, it is not a shorthand for a loop but the establishment of a direct channel between the caller and the inner generator for as long as it runs.
This property is exactly what made async possible: await is a direct descendant of yield from, and a chain of coroutines works because the channel is forwarded all the way through to the event loop.
Snippet D. A generator object stores a frame, not data: 200 bytes regardless of whether a million elements lie ahead or infinity.
| a million squares | memory |
|---|---|
| list comprehension | 40.4 MB |
| generator expression | 0.0004 MB |
A difference of a hundred thousand times — and that is exactly the arithmetic of lesson 03: a list holds pointers and objects, a generator holds nothing but a position. Hence also the fact that a generator can be infinite.
A generator is not always a gain. If you need a repeated traversal, a length, an index or a slice, the generator loses, and getting around that with list() brings back the original memory cost. Plus every step costs resuming the frame: on small collections a list is faster.
Iterability is not given by __iter__ alone. The old protocol through __getitem__ with integer indices still works — an object without __iter__ can be iterable, and that is not a bug but compatibility (lesson 11).
StopIteration inside a generator no longer propagates. Since 3.7 (PEP 479) it is turned into a RuntimeError: before, a stray StopIteration from a nested call silently cut a generator short, and that was a source of elusive bugs.
Root R5: traversal is expressed by one protocol, and everything else is built on top of it. The for loop, comprehensions, unpacking, in, zip, sum, sorted — all work through two methods and know nothing about the type of the source.
The history of its development is almost a straight line, and it is worth keeping in your head in full. The iterator protocol appeared in 2001 (PEP 234). Generators — also in 2001 (PEP 255), at first only as “a function that hands out values”. The two-way send was added in 2005 (PEP 342), and the generator became a coroutine in capability. yield from — in 2012 (PEP 380), and building chains became possible. And on top of that, in 2015, came the async/await syntax (PEP 492), which for a while was literally a layer over generators.
That is, all of Python's async grew out of the traversal protocol — not because it was planned that way, but because a suspended frame with a two-way channel turned out to be exactly what concurrency needs.
A generator is a C++20 coroutine, and the match is almost word for word. In both cases calling a function with a special keyword does not execute the body but creates an object that stores a frame: local variables, the resumption point, the stack. In both cases control returns to the caller, and the body continues only on an explicit resumption.
The difference is who pays for placing the frame. C++ gives control — the frame can be placed anywhere, and with luck the compiler eliminates it altogether — but requires writing a wrapper type with a promise_type. Python places the frame on the heap unconditionally, so a generator step costs resuming the frame, but there is nothing to write.
The second useful image is a lazy sequence, as in C++20 ranges or Java Streams: the elements do not exist until they are asked for. Hence the hundred-thousand-fold memory difference of consequence 4.
Questions that come up on their own if you read closely. The answer is under the question.
It could, and that is exactly what an iterable is. They are two different concepts, and that is precisely what gets confused.
An iterable (__iter__) is something you can walk; each call gives a new iterator. An iterator (__next__ plus an __iter__ that returns itself) is the position in the traversal itself. A position is by definition one, so a “restartable iterator” is a contradiction: two simultaneous passes would share one state.
l = [1, 2, 3]
print(iter(l) is iter(l)) # → False a list gives a new iterator
it = iter(l)
print(iter(it) is it) # → True an iterator returns itself
The split lets two loops walk one list independently — which is what happens in the nested loop for a in l: for b in l:.
The practical consequence people get caught on: a function that accepts a “sequence” and walks it twice silently breaks on a generator. The first pass eats everything, the second sees emptiness — with no exception:
def stats(xs):
return sum(xs) / len(list(xs)) # the second pass over an empty one
print(stats([1, 2, 3])) # → 2.0
print(stats(x for x in [1, 2, 3])) # → ZeroDivisionError
The cure is either materializing at the entry (xs = list(xs)), or a one-pass algorithm, or an honest annotation of Sequence instead of Iterable — then mypy will tell you.
yield from versus a loop with yield — why separate syntax?Because a loop forwards only values, while yield from builds a two-way channel.
A generator is not merely a source of values. You can send a value into it (send), throw an exception into it (throw), close it (close), and it can return a result through return. A loop loses all of this:
def inner():
got = yield 1
print("inner got:", got)
return "result"
def via_loop():
for v in inner(): yield v # send will not get through, return will be lost
def via_from():
r = yield from inner() # a channel all the way through
print("returned:", r)
g = via_from()
next(g)
try: g.send("hello")
except StopIteration: pass
# → inner got: hello
# → returned: result
With via_loop the inner generator would have received None, and the returned value would have vanished.
Why this was needed. PEP 380 made it possible to split a generator into sub-generators without losing semantics — that is, to refactor them like ordinary functions. And then await was built on the same mechanism: a coroutine waits for another coroutine exactly the way a generator delegates to a sub-generator. Lesson 14 is about this.
As a side effect, yield from is also faster: delegation goes directly, without passing the value through an intermediate frame on every step.
When the data is needed more than once, when you need a size, and when the work is small but the overhead of resuming the frame is not.
The saving is real and huge:
import tracemalloc
tracemalloc.start(); lst = [i*i for i in range(1_000_000)]
print(tracemalloc.get_traced_memory()[0] / 1e6, "MB"); tracemalloc.stop()
# → 40.4 MB
tracemalloc.start(); gen = (i*i for i in range(1_000_000))
print(tracemalloc.get_traced_memory()[0], "bytes"); tracemalloc.stop()
# → 408 bytes
Forty megabytes against four hundred bytes — and that is not an optimization but a different class of memory: for a generator it does not depend on the number of elements at all.
Where it does harm. You need len — a generator does not have it and cannot. You need a second pass — you will have to materialize, and then there was no saving. You need a slice or indexed access — no again. The data fits in memory and is walked many times — a list is simpler and faster.
And a separate case: laziness changes the moment of the error. A generator reading a file will fail not where it was created but where it is walked — possibly already outside the with, when the file is closed. This is the most common mistake with generators in real code:
def rows(path):
with open(path) as fh:
return (line.split(",") for line in fh) # the file closes before it is read
for r in rows("data.csv"): ... # ValueError: I/O operation on closed file
The cure is to replace return with yield from — then the with lives as long as the generator.
__iter__ hands out an iterator, __next__ hands out the next element and signals the end with an exception. An iterator keeps its position inside itself, so it is single-use — while a list hands out a new iterator on every for, so it can be traversed repeatedly; a function that walks its argument twice silently breaks on a generator. A function with yield executes not a single line when called; it creates an object with a suspended frame: work is done on demand, and an argument check inside a generator fires not where you expect it. yield is two-way — it takes a value in through send, an exception through throw, and gives a result through return — and an ordinary loop for v in inner(): yield v forwards only values outward, losing the rest; yield from builds a direct channel all the way through. This very property is what made await possible: all of Python's async grew out of the traversal protocol.C++ before C++20 solved the same task in a fundamentally different way: an iterator is a generalized pointer, and a traversal is given by a pair of iterators, begin and end. There is no end-as-an-exception, there is a comparison with end. Hence a C++ iterator is copyable and allows several independent passes, and hence it can be invalidated by a change to the container — in Python you get a RuntimeError about modification during iteration instead.
C++20 coroutines, on the other hand, are exactly consequences 2 and 3: a function containing co_yield is not executed when called but creates an object with a saved frame, and is resumed from outside. The difference is that C++ lets you choose where to place that frame and requires writing an intermediate type; Python places it on the heap and gives a ready protocol. One mechanism, two different prices.
Java did without generators altogether: Iterator with hasNext/next, and laziness came through the Stream API. Go, instead of generators, gives channels and goroutines — concurrency as the main mechanism, of which a lazy sequence is a special case. Python went exactly the other way: first a lazy sequence, and concurrency out of it.
A utility computes statistics. Someone passed it a generator instead of a list, and the report went to zero.
def summarize(rows):
total = sum(r.amount for r in rows)
count = len([r for r in rows if r.amount > 0]) # the second pass
return total, count
summarize(load_rows()) # load_rows is a generator
# (12345.0, 0)
The first pass exhausted the iterator, the second walked through emptiness. total is computed correctly, count is zero. No exception, no warning: consequence 1 in its pure form.
Review lets it through because both lines are correct on their own, and the tests almost certainly pass a list. It breaks at the joint, and partially — which is worse than a total failure: the report looks plausible and goes further.
Two ways to fix it, and the choice is meaningful. Materialize at the entry, if the data is known to fit in memory:
def summarize(rows):
rows = list(rows) # the contract: we work with everything at once
Or make one pass, if the data can be large:
def summarize(rows):
total = count = 0
for r in rows:
total += r.amount
if r.amount > 0:
count += 1
return total, count
The rule: if a function accepts an iterable and walks it more than once, it must either materialize it on its first line or declare Sequence rather than Iterable in its annotation — then the type checker will catch a generator being passed in ahead of time.
Typical data processing is written as a chain of list comprehensions. Swapping the brackets for parentheses changes the class of memory consumption.
rows = [parse(l) for l in open(path)] # the whole file in memory
valid = [r for r in rows if r.ok] # one more copy
result = [transform(r) for r in valid] # and one more
rows = (parse(l) for l in open(path))
valid = (r for r in rows if r.ok)
result = (transform(r) for r in valid)
for r in result: ... # only here does the work begin
| a million elements | memory |
|---|---|
| list comprehension | 40.4 MB |
| generator expression | 0.0004 MB |
The second variant creates not a single intermediate list: an element passes all three steps and is thrown away. Memory is constant and does not depend on the size of the file — you can process what does not fit in memory.
Note consequence 2 in action: the first three lines do not read the file at all. Work begins at the for, and that also means a parsing exception will arrive from there, not from the line with parse.
When not to do this: the data is needed several times (consequence 1), you need a length or sorting — sorted materializes anyway — or there are few elements and readability matters more. And a separate case: if a step makes network or disk calls, laziness smears those calls across the whole traversal, which can be worse than one batched request.
Run the four snippets and check them against your prediction. Then:
def g():
try:
yield 1
finally:
print("clean-up")
x = g(); next(x); del x
# When will “clean-up” be printed, and why exactly then?
def g2():
yield next(iter([]))
list(g2())
# StopIteration inside a generator. What will you get, and why not an empty list?
def g3():
while True:
try: yield 1
except ValueError: print("caught inside")
x = g3(); next(x); x.throw(ValueError)
# The exception was thrown from outside and caught inside. Where is this used in the standard library?
sum(i for i in range(10))
sum([i for i in range(10)])
# Measure both on a million. Why can the generator turn out slower?
The third question leads straight to lesson 12: @contextmanager is built on throw — an exception from the with block is thrown into the generator at the point of yield.
Lib/contextlib.py. We come back to it a second time, now from the other side. @contextmanager works because a generator can take an exception in: __exit__ calls gen.throw(exc), and the exception arises at the point of yield, where the body's try/finally catches it. Consequence 3 is not a theoretical possibility but the load-bearing structure of a whole module.
Modules/itertoolsmodule.c and its documentation. The “itertools recipes” section is three dozen short generators assembled from the basic ones: a sliding window, grouping, interleaving, splitting into batches. The value is not in the recipes themselves but in the principle you can see: a complex traversal is assembled by composing simple ones, and not a single step materializes the data.
Note tee — it solves exactly the problem from the “In practice” section: it makes several independent iterators out of one. And it honestly warns in the documentation that it buffers everything one consumer has already read and another has not yet. The problem does not go away; it becomes explicit.
From L1 you know that a generator keeps a suspended frame. Here: what is in it and what it costs.
A generator object contains a pointer to the frame, a state (created, running, suspended, closed), a name and a weak reference. The frame is the same as for an ordinary call: an array of local variables, the value stack, a pointer to the code object, and the position of the last executed instruction.
The key difference from an ordinary call: the frame of an ordinary function lives on the interpreter's frame stack and dies on return, while a generator's frame has to survive the return of control — so it is placed separately and retained by the generator object.
g = (i for i in range(1_000_000))
print(sys.getsizeof(g))
# → 200
g.gi_frame.f_lasti # the position of execution
g.gi_running # False while not inside next
Hence the price: a generator step means restoring the frame, executing up to yield, saving the position and returning. More expensive than taking an element from a list, which is why on small collections a list wins on time while losing on memory. The answer to the fourth question from “Check it yourself” comes from here too.
About clean-up. A generator with a try/finally, abandoned half-way, must execute its finally block. This is done by a call to close, which throws GeneratorExit inside — and that happens when the object is destroyed, that is, by the rules of lesson 09. So: in CPython the clean-up happens right when the last reference is lost, and on another implementation at some point 🔧. Exactly the same logic as with a file without with.
Tag v3.11.15.
Objects/genobject.c — the whole generator type: gen_send_ex (resuming the frame), gen_throw, gen_close. Three functions that close consequences 2 and 3.Python/ceval.c, the SEND and YIELD_VALUE instructions — how yield from is compiled into a loop of handing over control with no intermediate Python frame.yield: this is where the generator became a coroutine in capability.yield from; the motivation goes line by line through what a naive loop loses — snippet C of this lesson is taken from there.finally of an abandoned generator will runawait as a direct descendant of yield fromyield from differs from a loop, with the complete list of what gets lost.