send() Injects Values Into Running Generators

generators accept injected values through .send() after priming with next(), and close() ends them permanently by raising GeneratorExit inside.

PythonData Integrity

Code

pythonsnippet
24 lines
def averager():
    total = 0.0
    count = 0
    average = None
    while True:
        # yield both pauses the generator and receives the next .send() value
        value = yield average
        total += value
        count += 1
        average = total / count

avg = averager()
# the first next() "primes" the generator: it runs to the first yield and returns None
print(next(avg))
print(avg.send(10))
print(avg.send(20))
print(avg.send(30))

# close() raises GeneratorExit inside the generator and stops it for good
avg.close()
try:
    avg.send(40)
except StopIteration:
    print("sends after close raise StopIteration")

How it works

The code’s whole job belongs to the function averager.

The one repetition in this snippet is the loop while True. A StopIteration is raised unconditionally at its raise site — no input check sits in front of it.

Watch out for

  • No external packages — everything relies on the language’s built-in APIs.

Using it

Signature: def averager()

Running the file prints labeled results such as sends after close raise StopIteration — each operation’s effect is visible in the output.

averager is the public entry point; everything else in the file exists to support it.

Key statements

except StopIteration:
    print("sends after close raise StopIteration")
def averager():
    total = 0.0
    count = 0
    average = None
    while True:
        # yield both pauses the generator and receives the next .send() value
        value = yield average
        total += value
        count += 1
        average = total / count

Interactive Tools for This Topic

FAQ

Does the code guard against bad input?
The snippet does not validate input. `StopIteration` is thrown unconditionally at its throw site — nothing guards it.
Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. The file defines `averager` at load time.