Generator Based Coroutines · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What makes coroutines cooperative multitasking, as opposed to threads?
2. What does this print?
from inspect import getgeneratorstate

def gen():
    yield 1

g = gen()
print(getgeneratorstate(g), end=' ')
next(g)
print(getgeneratorstate(g), end=' ')
next(g, None)
print(getgeneratorstate(g))
3. What does this print?
def gen():
    print('A')
    x = yield 1
    print('B', x)
    yield 2

g = gen()
print(next(g))
print(g.send('hi'))
4. What happens here?
def echo():
    while True:
        received = yield
        print(received)

e = echo()
try:
    e.send('hello')
except TypeError as ex:
    print('TypeError')
5. Which call is exactly equivalent to next(g)?
6. What does this print?
def gen():
    try:
        while True:
            yield
    except GeneratorExit:
        print('closing')
        yield 'one more'

g = gen()
next(g)
try:
    g.close()
except RuntimeError:
    print('RuntimeError')
7. Why doesn't except Exception: inside a generator interfere with close()?
8. What does this print?
def gen():
    while True:
        try:
            yield 'ready'
        except ValueError:
            print('handled')

g = gen()
next(g)
print(g.throw(ValueError('oops')))
9. What does this print?
def sub():
    yield 1
    return 'done'

def delegator():
    result = yield from sub()
    yield result

print(list(delegator()))
10. What does this print?
def sub():
    try:
        while True:
            yield
    finally:
        print('sub closed')

def delegator():
    yield from sub()
    print('after yield from')

d = delegator()
next(d)
d.close()
11. In a push pipeline of coroutines like source → transform → filter → sink, which statement is true?
12. Modern asyncio code is written with async def and await. How do they relate to the generator-based coroutines in this section?

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: A priming decorator

Write a decorator coroutine for generator functions. Calling the decorated function should create the generator, prime it (advance it to its first yield) and return it, so it's ready for send() straight away.

It must forward any positional and keyword arguments, and it should keep the decorated function's __name__ and __doc__.

Hints (2)
  1. Priming means calling next() once on the new generator before returning it.
  2. functools.wraps(gen_fn) copies the name and docstring onto inner.
Show a solution
from functools import wraps

def coroutine(gen_fn):
    @wraps(gen_fn)
    def inner(*args, **kwargs):
        gen = gen_fn(*args, **kwargs)
        next(gen)
        return gen
    return inner

Exercise 2: A total you can reset and close

Write a generator-based coroutine running_total():

- after priming, each send(x) adds x to a running total and yields the new total; - throwing the provided Reset exception into it (t.throw(Reset)) sets the total back to 0, and throw returns 0; the coroutine keeps working afterwards; - closing it with t.close() returns the final total (Python 3.13+ returns the value a generator returns while handling GeneratorExit).

Use a single yield in your loop.

Hints (2)
  1. Put a try/except Reset around the yield inside the loop, so after a reset the loop comes back to the same yield (which then yields 0).
  2. Wrap the whole loop in try/except GeneratorExit and return total there. That value becomes the result of close().
Show a solution
class Reset(Exception):
    pass

def running_total():
    total = 0
    try:
        while True:
            try:
                x = yield total
                total += x
            except Reset:
                total = 0
    except GeneratorExit:
        return total

Exercise 3: Flatten anything (but not strings)

Write a generator flatten(item) that lazily yields every non-iterable value from an arbitrarily nested structure of iterables (lists, tuples, sets, generators, …), in order, using recursive yield from.

Strings are atoms: yield a string whole, never its characters. A non-iterable top-level argument is yielded as is.

Hints (2)
  1. Test for "iterable" by trying iter(item) and catching TypeError.
  2. Check for str before the iterable test, otherwise single characters recurse forever.
Show a solution
def flatten(item):
    if isinstance(item, str):
        yield item
        return
    try:
        it = iter(item)
    except TypeError:
        yield item
        return
    for x in it:
        yield from flatten(x)

Exercise 4: Broadcast and filter

Complete two auto-primed coroutines for a push pipeline (the coroutine decorator and a collect sink are provided):

- filter_data(predicate, target): for every received item, send it to target only if predicate(item) is true; - broadcast(targets): send every received item to each target, in order.

Both must close their targets when they are closed themselves, so closing the head of a pipeline shuts down every stage.

Hints (2)
  1. Each stage forwards data with target.send(item).
  2. Wrap the loop in try/finally and call close() on the target(s) in the finally block. close() raises GeneratorExit at the yield, so the finally runs.
Show a solution
def coroutine(fn):
    def inner(*args, **kwargs):
        g = fn(*args, **kwargs)
        next(g)
        return g
    return inner

@coroutine
def collect(results):
    while True:
        results.append((yield))

@coroutine
def filter_data(predicate, target):
    try:
        while True:
            item = yield
            if predicate(item):
                target.send(item)
    finally:
        target.close()

@coroutine
def broadcast(targets):
    try:
        while True:
            item = yield
            for target in targets:
                target.send(item)
    finally:
        for target in targets:
            target.close()