yield — Expert Examples
Pauses a generator function and produces a value to the caller
Coroutine-style generators
Using send() and throw() to create coroutines.
python
def running_average(): total = 0 count = 0 average = None while True: value = yield average if value is None: break total += value count += 1 average = total / count # Drive the coroutine gen = running_average() next(gen) # Prime the generator for v in [10, 20, 30, 40, 50]: avg = gen.send(v) print(f"Added {v}, running average: {avg}") # Generator state inspection import inspect def simple(): yield 1 yield 2 g = simple() print(f"\nState: {inspect.getgeneratorstate(g)}") next(g) print(f"State: {inspect.getgeneratorstate(g)}") list(g) print(f"State: {inspect.getgeneratorstate(g)}")
gen.send(value) resumes the generator and passes a value in through the yield expression. This enables coroutine-style bidirectional communication.
Want to try these examples interactively?
Open Expert Playground