Sub topic 14
Return values from generators
This chapter assumes you can write generator functions with yield, know what StopIteration is, and have seen yield from at a basic level. It covers how a generator hands back a final value, where that value goes, and the mistakes that follow from it.
A return statement inside a generator
A generator function can contain return value. The value is not produced by the loop. It is attached to the StopIteration exception that ends the generator, in the attribute StopIteration.value.
def counter():
yield 1
yield 2
return "finished"
gen = counter()
print(next(gen)) # 1
print(next(gen)) # 2
try:
next(gen)
except StopIteration as stop:
print(stop.value) # finishedA bare return, or running off the end of the function, gives a value of None.
Why a for loop never shows it
A for loop catches StopIteration itself and uses it only as the signal to stop. It throws the exception away, so the return value is lost. The same applies to list(), sum() and every other consumer that loops for you.
def counter():
yield 1
yield 2
return "finished"
print(list(counter())) # [1, 2]The string "finished" does not appear in the list. To read the return value you must call next() yourself and catch StopIteration, or use yield from.
Capturing the value with yield from
The expression yield from sub forwards every value from sub to the caller. When sub finishes, the whole yield from expression evaluates to the return value of sub. Python reads it from StopIteration.value for you.
def inner():
yield 1
yield 2
return "done"
def outer():
result = yield from inner()
print(result)
print(list(outer())) # prints "done", then [1, 2]Here outer receives "done" in the variable result. The caller of outer still sees only 1 and 2.
A practical use: values plus a summary
Delegation lets a sub-generator stream items and also report a summary, such as a count, once it has finished.
def read_items(items):
count = 0
for item in items:
yield item
count += 1
return count
def report(items):
total = yield from read_items(items)
yield f"total: {total}"
print(list(report(["a", "b", "c"]))) # ['a', 'b', 'c', 'total: 3']The caller gets one stream. The summary is added at the end by the delegating generator.
Common errors
- Expecting
forto return it. Loops andlist()discard the value. Useyield fromor catchStopIteration. - Reading
.valuebefore the end.StopIterationis raised only when the generator finishes. Until then there is no value to read. - Calling
next()again after exhaustion. Each further call raisesStopIterationagain, but withvalueset toNone. The original return value is available only from the first exception. - Using
return valuein Python 2 style code. This was a syntax error before Python 3.3. The feature needs Python 3.3 or later.
Summary of the mechanism
| Situation | What happens to the return value |
|---|---|
| `for` loop or `list()` | Discarded |
| `next()` with `try/except StopIteration as e` | Available as `e.value` |
| `result = yield from sub` | Assigned to `result` |
| Bare `return` or end of function | Value is `None` |
Exercise
What does this code print? def gen(): yield "a" return "b" def wrapper(): got = yield from gen() yield got print(list(wrapper()))
Show answer
It prints ['a', 'b']. The generator gen yields "a" and then returns "b". The expression yield from gen() forwards "a" to the caller and then evaluates to "b", which is stored in got. The wrapper then yields got, so the final list contains both values.
Exercise
Write code that runs a generator by hand with next() and prints its return value, without using yield from.
Show answer
Call next() in a loop and catch StopIteration: def gen(): yield 1 return "result" g = gen() while True: try: next(g) except StopIteration as stop: print(stop.value) # result break