Sub topic 14
Return values from generators
This chapter assumes you can write a generator function with yield, you know that next() raises StopIteration when a generator finishes, and you have seen yield from used to delegate to another generator. Earlier chapters covered all three.
A generator can return a value
A generator function can contain return value. This is legal in Python 3.3 and later. The returned value is not produced by the loop that consumes the generator. It is stored on the StopIteration exception that signals exhaustion, in the attribute value.
def count_to(n):
for i in range(1, n + 1):
yield i
return "finished"
gen = count_to(2)
print(next(gen)) # 1
print(next(gen)) # 2
try:
next(gen)
except StopIteration as exc:
print(exc.value) # finishedThe two values 1 and 2 are yielded. The string "finished" is not yielded. It travels with the exception that ends the iteration.
A for loop catches StopIteration internally and throws it away. So for, list(), sum(), and every other consumer that loops quietly discard the return value:
print(list(count_to(2))) # [1, 2]The return value is only visible if you call next() or send() yourself and catch the exception, or if you use yield from.
What the value is when you do not return one
A generator that ends without a return statement, or with a bare return, produces StopIteration with value set to None. The same applies to every later call to next() on an exhausted generator. The real return value is delivered only once, on the call that finishes the generator.
gen = count_to(0) # the loop body never runs
try:
next(gen)
except StopIteration as exc:
print(exc.value) # finished
try:
next(gen)
except StopIteration as exc:
print(exc.value) # NoneIf you need the value, capture it the first time. It cannot be retrieved afterwards.
Reading the value by hand
A small helper shows the whole mechanism. It drains a generator and returns both the yielded items and the return value:
def numbers(limit):
total = 0
for n in range(limit):
yield n
total += n
return total
def collect(gen):
items = []
while True:
try:
items.append(next(gen))
except StopIteration as exc:
return items, exc.value
print(collect(numbers(4))) # ([0, 1, 2, 3], 6)Here the generator yields each number and also computes a summary (the total) that is only complete when the iteration ends. Returning the summary avoids a separate pass over the data and avoids exposing a mutable variable that the caller would have to share with the generator.
yield from: the normal way to receive the value
Handling StopIteration manually is rarely needed, because yield from does it for you. The expression yield from sub forwards every value that sub yields to the caller of the outer generator. When sub finishes, the whole yield from expression evaluates to sub's return value.
def inner():
yield 1
yield 2
return "done"
def outer():
result = yield from inner()
print(result)
print(list(outer())) # prints "done", then [1, 2]The order of output matters. print(result) runs while list() is still consuming outer(), which is why done appears before the list is printed.
The outer generator can then do more work with the value and return something of its own:
def numbers(limit):
total = 0
for n in range(limit):
yield n
total += n
return total
def report():
total = yield from numbers(4)
print("sum:", total)
return total * 2
gen = report()
print(list(gen)) # prints "sum: 6", then [0, 1, 2, 3]report() yields the values of numbers(4) unchanged, uses the sub-generator's total, and finishes with a return value of its own, 12. list() discards that value, as before.
Where the value goes: a summary
| Consumer | What happens to the return value |
|---|---|
| `for` loop, `list()`, `sum()`, `tuple()` | Discarded |
| `next()` with `try/except StopIteration as exc` | Available as `exc.value` |
| `send()` with `try/except StopIteration as exc` | Available as `exc.value` |
| `result = yield from sub` | Becomes `result` in the outer generator |
Using returns to build structured results
A common pattern is a generator that streams items and also reports a final status. For example, a parser might yield records one by one and return how many lines it skipped:
def parse(lines):
skipped = 0
for line in lines:
if not line.strip():
skipped += 1
continue
yield line.strip()
return skipped
def process(lines):
skipped = yield from parse(lines)
yield f"skipped {skipped} blank lines"
print(list(process(["a", "", "b", " "])))
# ['a', 'b', 'skipped 2 blank lines']parse() stays lazy. The caller sees records as they arrive, and the summary is available as soon as the stream ends. If you need to return several results, return a tuple or a small dataclass. The value attribute holds exactly one object.
Pitfalls
Raising StopIteration inside a generator
You might think that raising StopIteration by hand is another way to end a generator with a value. It is not. Since Python 3.7 (PEP 479), a StopIteration that escapes from a generator body is converted into a RuntimeError:
def broken():
yield 1
raise StopIteration("oops")
try:
list(broken())
except RuntimeError as exc:
print(exc) # generator raised StopIterationUse return "oops" instead. The conversion exists so that a stray StopIteration from a call such as next(other_iterator) inside your generator does not silently cut the output short.
Expecting the value from a loop
If code like result = [x for x in gen] is meant to give you the return value, it will not. Either switch to yield from, which works only inside another generator, or use a helper like collect() above.
Return in a function that is not a generator
A function is a generator only if its body contains yield or yield from. A function with return 5 and no yield is an ordinary function. It returns 5 directly, and nothing is wrapped in StopIteration. Conversely, adding a yield anywhere in the body, even in a branch that never runs, makes the whole function a generator, and return 5 then sets StopIteration.value.
def maybe(flag):
if flag:
return 5
yield 1 # never reached, but makes maybe() a generator
gen = maybe(True)
try:
next(gen)
except StopIteration as exc:
print(exc.value) # 5Reading exc.value versus exc.args
StopIteration(5).value is 5, and exc.args is (5,). Prefer exc.value, which is the documented attribute. For a generator that returns nothing it is None, while args is an empty tuple.
Design guidance
Use a generator return value when all three of these hold:
- The summary is only known after the last item has been produced, such as a total, a count, or a final state.
- The caller is another generator that uses
yield from, or code that drives the generator manually. - Items still need to stream lazily, so building a full list and returning it would defeat the purpose.
Avoid it when ordinary consumers, such as for loops, need the summary. They cannot see it. In that case, make the generator a method of a class and store the summary in an attribute, or yield a final sentinel item as process() did above.
Exercise
What does this program print? def g(): yield "a" return "b" def h(): x = yield from g() yield x print(list(h()))
Show answer
It prints ['a', 'b']. The generator h() forwards "a" from g(). When g() returns "b", the yield from expression evaluates to "b" and is stored in x, and h() then yields x as its own second item.
Exercise
Write a generator function evensandcount(numbers) that yields each even number from an iterable and returns how many odd numbers it skipped. Then show how to read the skipped count without using yield from.
Show answer
One solution: def evensandcount(numbers): skipped = 0 for n in numbers: if n % 2 == 0: yield n else: skipped += 1 return skipped gen = evensandcount([1, 2, 3, 4, 5]) evens = [] while True: try: evens.append(next(gen)) except StopIteration as exc: skipped = exc.value break print(evens, skipped) # [2, 4] 3 The count is read from exc.value on the StopIteration that ends the generator.