Read Generator Completion Values
Core idea
return value ends a synchronous generator; the completion exception StopIteration carries that value in its value attribute. A for loop and list conversion consume only yielded items. result = yield from child() receives the child completion value. Do not explicitly raise StopIteration in a generator body to finish it: an escaping StopIteration becomes RuntimeError.
def scan(): yield "A" return 7g = scan()print(next(g))try: next(g)except StopIteration as exc: print(exc.value)The number is completion metadata, not another yielded item.
Receive a delegated result
def child(): yield 2 return 8def parent(): total = yield from child() yield total + 1print(list(parent()))The parent explicitly turns the completion value into a new yielded item.
Intentional failure: raising StopIteration
def broken(): if False: yield 1 raise StopIteration(4)next(broken())The yield marks this as a generator even though that branch does not execute. Python transforms the escaping exception.
Common mistake
Do not expect list(g) to include a generator return value, or expect repeated next calls to preserve the original completion value. Capture it on the completion call.
Practice
Make a generator yield two counts and return their total. Capture the total using yield from and compare with list conversion.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generator completion values
Check your understanding of generator return values.
What is printed?
def items(): yield 3 return 9print(list(items()))What is printed?
def items(): if False: yield 1 return 6try: next(items())except StopIteration as exc: print(exc.value)What happens?
def broken(): if False: yield 1 raise StopIteration(3)next(broken())What does result = yield from child() receive on normal child completion?