CodeBlanks Logo Icon CodeBlanks

send and throw

Learn generator interaction with send() and throw().

The send method

A generator can receive values from outside. The g.send(value) call sends a value to the awaited yield expression and advances to the next yield. This lets generators act as coroutines.

Example: v = yield total. The call g.send(5) assigns 5 to v. Before the first send, you must call next(g) to advance the generator to the first yield; this is called priming.

The throw method

The g.throw(Exception) call raises an exception at the awaited yield point in the generator. The generator can catch it with try/except or let it propagate up.

Example: if the generator body is try:\n v = yield total\nexcept ValueError:\n print("error"), the call g.throw(ValueError) runs the except block. This is used to signal errors into the generator from outside; it is practical for cancellation or state changes in long-running tasks.

Practice acc generator and send

Define the function def acc():. In the body write total = 0; open a while True: loop; inside write v = yield total and if v is not None: total += v. Create an instance with g = acc(), prime with next(g). Send two values and print the result with print(g.send(5)) and print(g.send(10)).

Starter code

main.py
# acc generator and accumulate with send

Sample solution

main.py
# acc generator and accumulate with send
def acc():
    total = 0
    while True:
        v = yield total
        if v is not None:
            total += v

g = acc()
next(g)
print(g.send(5))
print(g.send(10))

Expected output

5
15

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the send and throw parts

Term Meaning
send Sends a value
throw Raises an error
next(g) Priming
v = yield Receive value

2 What happens before send is called?

  • The generator is deleted
  • It is primed with next(g) Correct answer
  • throw is called
  • close is called

Explanation: This is known as priming.

3 send call

Question
g = acc()
next(g)
print(g.____(5))
Answer
g = acc()
next(g)
print(g.send(5))

Explanation: g.send(5) sends 5 into the generator.

All lessons in Intermediate