This is a new feature in Python 3.3 (as a comment notes, it doesn’t even work in 3.2). Much like return
in a generator has long been equivalent to raise StopIteration()
, return <something>
in a generator is now equivalent to raise StopIteration(<something>)
. For that reason, the exception you’re seeing should be printed as StopIteration: 3
, and the value is accessible through the attribute value
on the exception object. If the generator is delegated to using the (also new) yield from
syntax, it is the result. See PEP 380 for details.
def f():
return 1
yield 2
def g():
x = yield from f()
print(x)
# g is still a generator so we need to iterate to run it:
for _ in g():
pass
This prints 1
, but not 2
.