defrunning_average():
total = 0
count = 0
average = NonewhileTrue:
value = yield average
if value isNone:
break
total += value
count += 1
average = total / count
# Drive the coroutine
gen = running_average()
next(gen) # Prime the generatorfor v in [10, 20, 30, 40, 50]:
avg = gen.send(v)
print(f"Added {v}, running average: {avg}")
# Generator state inspectionimport inspect
defsimple():
yield1yield2
g = simple()
print(f"\nState: {inspect.getgeneratorstate(g)}")
next(g)
print(f"State: {inspect.getgeneratorstate(g)}")
list(g)
print(f"State: {inspect.getgeneratorstate(g)}")
Output
Click "Run" to execute your code
gen.send(value) resumes the generator and passes a value in through the yield expression. This enables coroutine-style bidirectional communication.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?