CKTIS / Python
Keyword yield
In an ordinary function, yield makes calling it create a generator rather than execute the body immediately.
Version: Python 3.14; repository image, production runtime not attested
Syntax
value = yield itemIn an ordinary function, yield makes calling it create a generator rather than execute the body immediately.
Each yield exposes a value and suspends with local state intact. send(x) supplies the result of the paused yield expression and returns the next emitted value if one exists. Generator return terminates with StopIteration.value. Prime a new generator using next or send(None), since any other initial value raises TypeError.
A yield from expression forwards send to a suspended subgenerator and receives its return value.
Examples
def exchange():
response = yield "ready"
yield response * 2
return "closed"
g = exchange()
print(next(g), g.send(4))
try:
next(g)
except StopIteration as end:
print(end.value)
def relay():
done = yield from exchange()
yield "child " + done
g = relay()
try:
g.send(3)
except TypeError:
pass
else:
raise AssertionError("unprimed generator")
assert g.send(None) == "ready" and g.send(3) == 6 and next(g) == "child closed"
Result
ready 8 closed
A yield from expression forwards send to a suspended subgenerator and receives its return value.