SyntaxStudy
Sign Up
Python Sending Values to Generators
Python Advanced 5 min read

Sending Values to Generators

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.

Example
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
Pro Tip

Always prime a generator with next() before calling send() with a non-None value.