Sending objects to a generator

suggest change

In addition to receiving values from a generator, it is possible to send an object to a generator using the send() method.

def accumulator():
    total = 0
    value = None
    while True:
        # receive sent value
        value = yield total
        if value is None: break
        # aggregate values
        total += value

generator = accumulator()

# advance until the first "yield"
next(generator)      # 0

# from this point on, the generator aggregates values
generator.send(1)    # 1
generator.send(10)   # 11
generator.send(100)  # 111
# ...

# Calling next(generator) is equivalent to calling generator.send(None)
next(generator)      # StopIteration

What happens here is the following:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents