`yield` and `yield from`
yield hands one value out of a function and pauses it, keeping its local variables alive until someone asks for the next value. yield from delegates to another generator, forwarding values out and inputs in, and evaluates to that generator's return value.
Detailed Explanation
A return ends a function. yield suspends it. That one-word difference is the whole idea: when execution reaches yield, the value goes to the caller, the frame is frozen in place, and the next request resumes on the following line with every local variable exactly as it was.
The presence of yield anywhere in a body changes what the function is — it becomes a generator function, and calling it produces a generator object rather than running anything. The generators entry covers that object and why laziness matters. This entry is about the keyword itself.
yield is an expression, not only a statement. value = yield average sends average out and then waits; when the consumer calls send(x), the paused yield evaluates to x and execution continues. Plain iteration with next() is equivalent to send(None), which is why the variable is None in ordinary generators. Because it is an expression, you must parenthesise it inside a larger expression: total += (yield).
A generator may also return. The returned object is not yielded; it is attached to the StopIteration that terminates the generator, as StopIteration.value. A for loop discards it silently. This looks like a wart until you meet yield from.
Before Python 3.3, delegating to a sub-generator meant writing the loop by hand: for item in inner(): yield item. That works for values and nothing else. It drops the sub-generator's return value, it does not forward send() or throw(), and it adds a stack frame per level, so a recursive tree walk got quadratically slower with depth.
yield from inner() replaces that loop and fixes all of it. Values flow out, send and throw flow in, exceptions propagate correctly, and the whole expression evaluates to whatever inner() returned. This is what makes recursive generators pleasant: flattening a nested structure is three lines.
Two more control methods complete the picture. gen.throw(SomeError) raises an exception at the paused yield, letting the generator handle it or clean up. gen.close() raises GeneratorExit there, which is how a finally block inside a generator gets its chance to release a file or lock. If you swallow GeneratorExit and try to yield again, CPython raises RuntimeError.
Historically this machinery carried Python's first coroutines. Pre-3.5 asyncio used yield from to suspend on a future, and async def / await is the same suspend-and-resume mechanism given dedicated syntax and a separate object type. Knowing yield from makes await feel familiar rather than magical.
The cost of two-way generators is comprehension. A generator you only iterate over is easy to read. A generator driven by send() is a small state machine with no obvious entry point, and most such code is clearer as a class with a method, or as async def. Reach for send() when you genuinely want a consumer that accumulates pushed values; reach for plain yield the rest of the time.
Finally, a syntax rule: yield is only legal inside a function body. It is a SyntaxError at module level, in a class body, and inside a comprehension.
Code Examples
def checkout_steps():
print("reserving stock")
yield "reserved" # pause here, hand "reserved" out
print("charging card")
yield "charged"
print("emailing receipt")
return "order-9001" # NOT yielded: rides on StopIteration
steps = checkout_steps() # nothing printed: the body has not started
print(next(steps))
# reserving stock
# reserved
print(next(steps)) # resumes on the line after the first yield
# charging card
# charged
try:
next(steps)
except StopIteration as stop:
print(stop.value)
# emailing receipt
# order-9001 <- the return value, invisible to a for loopdef read_shard(shard_id):
for row in range(2):
yield f"shard{shard_id}-row{row}"
return shard_id * 10 # a sub-generator may return a value
def read_all(shard_ids):
row_counts = []
for shard_id in shard_ids:
total = yield from read_shard(shard_id) # delegate AND capture the return
row_counts.append(total)
yield f"counts={row_counts}"
print(list(read_all([1, 2])))
# ['shard1-row0', 'shard1-row1', 'shard2-row0', 'shard2-row1', 'counts=[10, 20]']
# The pre-3.3 spelling: correct for values, but the return value is lost.
def read_all_manual(shard_ids):
for shard_id in shard_ids:
for row in read_shard(shard_id):
yield row
print(list(read_all_manual([1]))) # ['shard1-row0', 'shard1-row1']
# yield from makes recursive generators short.
def flatten(nested):
for item in nested:
if isinstance(item, list):
yield from flatten(item) # recurse without a manual re-yield loop
else:
yield item
print(list(flatten([1, [2, [3, [4]], 5], 6]))) # [1, 2, 3, 4, 5, 6]def running_average():
"""Here `yield` is an expression: it evaluates to whatever send() passes in."""
total = 0.0
count = 0
average = None
try:
while True:
new_reading = yield average # hand out the average, wait for input
total += new_reading
count += 1
average = total / count
finally:
# Runs on close() or garbage collection. This is where you release things.
print(f"averager closed after {count} readings")
latency = running_average()
print(next(latency)) # None <- priming: run up to the first yield
print(latency.send(100)) # 100.0
print(latency.send(50)) # 75.0
print(latency.send(30)) # 60.0
latency.close() # raises GeneratorExit at the paused yield
# averager closed after 3 readings
try:
latency.send(10) # a closed generator is finished for good
except StopIteration:
print("generator is done") # generator is doneCommon Gotchas
`send()` needs a primed generator
a brand-new generator is paused *before* the first line, so there is no `yield` waiting to receive a value. `gen.send(5)` on a fresh generator raises `TypeError: can't send non-None value to a just-started generator`. Call `next(gen)` (or `gen.send(None)`) once first.
A leaked `StopIteration` becomes `RuntimeError`
since Python 3.7 (PEP 479), if `StopIteration` escapes a generator body it is converted to `RuntimeError: generator raised StopIteration`. This bites when you call bare `next(inner)` inside a generator. Pass a default — `next(inner, None)` — or catch it locally.
`return` values are invisible to `for`
`for row in gen:` discards `StopIteration.value` completely. The only ways to see it are `yield from` or catching `StopIteration` yourself, so never put required output in a generator's `return` if plain iteration is the expected usage.
`yield from` is delegation, not concurrency
it runs the sub-generator in the same thread, one value at a time. Nothing overlaps. If you want overlapping I/O you want `async` / `await` or a thread pool, which is a different mechanism that happens to share this suspend-and-resume shape.