Sending Values to Generators
The send() method sends a value into a generator at the point of the last yield. The generator resumes and the sent value becomes the result of the yield expression.
The send() method sends a value into a generator at the point of the last yield. The generator resumes and the sent value becomes the result of the yield expression.
def accumulator():
total = 0
while True:
value = yield total
if value is None:
break
total += value
gen = accumulator()
next(gen) # prime the generator
print(gen.send(10)) # 10
print(gen.send(5)) # 15
Always prime a generator with next() before calling send() with a non-None value.