Generator Based Coroutines · Practice
Quiz & exercises
Answer each question to see the explanation. Your best score is saved in this browser.
Quiz
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 ✓ Passed
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__.
def coroutine(gen_fn):
def inner(*args, **kwargs):
# create the generator and return it
return gen_fn(*args, **kwargs)
return inner
from inspect import getgeneratorstate
@coroutine
def echo():
"""Echo back what it receives."""
received = None
while True:
received = yield received
@coroutine
def scaler(factor, *, offset=0):
result = None
while True:
x = yield result
result = x * factor + offset
def test_primed():
"""the returned generator is already suspended"""
e = echo()
assert getgeneratorstate(e) == 'GEN_SUSPENDED', f"state is {getgeneratorstate(e)}"
def test_send_works():
"""send() works immediately"""
e = echo()
assert e.send('hi') == 'hi'
def test_arguments():
"""positional and keyword arguments are forwarded"""
s = scaler(3, offset=1)
assert s.send(2) == 7, "expected 2 * 3 + 1"
def test_metadata():
"""keeps __name__ and __doc__"""
assert echo.__name__ == 'echo', f"__name__ is {echo.__name__!r}"
assert echo.__doc__ == 'Echo back what it receives.'
Hints (2)
- Priming means calling
next()once on the new generator before returning it. functools.wraps(gen_fn)copies the name and docstring ontoinner.
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 innerExercise 2: A total you can reset and close ✓ Passed
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.
class Reset(Exception):
pass
def running_total():
total = 0
while True:
x = yield total
total += x
def make():
t = running_total()
first = next(t)
return t, first
def test_prime_yields_zero():
"""priming yields the initial total 0"""
t, first = make()
assert first == 0, f"priming yielded {first!r}"
def test_running_total():
"""send() yields the running total"""
t, _ = make()
assert [t.send(x) for x in (5, 10, -3)] == [5, 15, 12]
def test_reset():
"""throw(Reset) returns 0 and the coroutine keeps working"""
t, _ = make()
t.send(5)
t.send(5)
assert t.throw(Reset) == 0, "throw(Reset) should return 0"
assert t.send(4) == 4, "total should restart from 0 after a reset"
def test_close_returns_total():
"""close() returns the final total"""
t, _ = make()
t.send(2)
t.send(3)
assert t.close() == 5, "close() should return the final total"
def test_closed_after_close():
"""the coroutine is closed after close()"""
from inspect import getgeneratorstate
t, _ = make()
t.close()
assert getgeneratorstate(t) == 'GEN_CLOSED'
Hints (2)
- Put a
try/except Resetaround theyieldinside the loop, so after a reset the loop comes back to the sameyield(which then yields0). - Wrap the whole loop in
try/except GeneratorExitandreturn totalthere. That value becomes the result ofclose().
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 totalExercise 3: Flatten anything (but not strings) ✓ Passed
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.
def flatten(item):
if isinstance(item, list):
for x in item:
yield from flatten(x)
else:
yield item
def test_nested_lists():
"""nested lists are flattened in order"""
assert list(flatten([1, [2, [3, [4]]], 5])) == [1, 2, 3, 4, 5]
def test_other_iterables():
"""tuples and generators are flattened too"""
data = [1, (2, 3), [4, (x for x in (5, 6))]]
assert list(flatten(data)) == [1, 2, 3, 4, 5, 6]
def test_strings_are_atoms():
"""strings are yielded whole"""
assert list(flatten(['ab', ['cd', ('e',)]])) == ['ab', 'cd', 'e']
def test_scalar():
"""a non-iterable argument is yielded as is"""
assert list(flatten(42)) == [42]
def test_lazy():
"""it is lazy: works on an infinite iterable"""
import itertools
out = list(itertools.islice(flatten([[0], itertools.count(1)]), 4))
assert out == [0, 1, 2, 3], f"got {out}"
Hints (2)
- Test for "iterable" by trying
iter(item)and catchingTypeError. - Check for
strbefore 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 ✓ Passed
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.
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):
while True:
item = yield
# your code here
@coroutine
def broadcast(targets):
while True:
item = yield
# your code here
from inspect import getgeneratorstate
def test_filter():
"""filter_data forwards only matching items"""
out = []
f = filter_data(lambda x: x % 2 == 0, collect(out))
for i in range(7):
f.send(i)
assert out == [0, 2, 4, 6], f"got {out}"
def test_broadcast():
"""broadcast sends every item to every target"""
a, b = [], []
bc = broadcast([collect(a), collect(b)])
for c in 'xyz':
bc.send(c)
assert a == ['x', 'y', 'z'] and b == ['x', 'y', 'z'], f"got {a}, {b}"
def test_split():
"""broadcast into several filters splits one stream"""
evens, big = [], []
head = broadcast([
filter_data(lambda x: x % 2 == 0, collect(evens)),
filter_data(lambda x: x > 6, collect(big)),
])
for i in range(10):
head.send(i)
assert evens == [0, 2, 4, 6, 8], f"evens: {evens}"
assert big == [7, 8, 9], f"big: {big}"
def test_close_chain():
"""closing the head closes every stage"""
sink = collect([])
flt = filter_data(lambda x: True, sink)
head = broadcast([flt])
head.close()
assert getgeneratorstate(flt) == 'GEN_CLOSED', "filter was not closed"
assert getgeneratorstate(sink) == 'GEN_CLOSED', "sink was not closed"
Hints (2)
- Each stage forwards data with
target.send(item). - Wrap the loop in
try/finallyand callclose()on the target(s) in thefinallyblock.close()raisesGeneratorExitat theyield, so thefinallyruns.
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()