Project 6 · Practice

Quiz & exercises

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

Quiz

1. In the push version of the car pipeline, which component drives the data flow?
2. Why must the chain of filter coroutines be built starting from the sink?
3. What does this print?
preds = []
for word in ('Chevrolet', 'Carlo'):
    preds.append(lambda name: word in name)

print([p('Chevrolet Impala') for p in preds])
4. What does this print?
import csv, io

buf = io.StringIO()
def save(f):
    writer = csv.writer(f)
    while True:
        row = yield
        writer.writerow(row)

s = save(buf)
next(s)
s.send(['Ford Torino', '17.0'])
s.send(['AMC Hornet', '18.0'])
print(repr(buf.getvalue()))
5. The pipeline coroutine has received every row, but the output file is still empty when you read it. What's the most likely cause?
6. What does this print?
from contextlib import contextmanager

def coro():
    try:
        while True:
            yield
    finally:
        print('coro closed')

@contextmanager
def managed():
    c = coro()
    next(c)
    try:
        yield c
    finally:
        c.close()

try:
    with managed() as c:
        c.send(1)
        raise ValueError('bad row')
except ValueError:
    print('error handled')

Coding exercises

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

Exercise 1: The data source

Write a generator parse_data(f_name) that opens the CSV file f_name, detects its dialect with csv.Sniffer (from the first 2000 characters), skips the header row, and yields each data row as a list of strings.

It must close the file when it finishes or is closed early. cars.csv (semicolon-separated, 406 data rows) is available in the working directory.

Hints (2)
  1. csv.Sniffer().sniff(f.read(2000)) returns a dialect; call f.seek(0) afterwards to go back to the start.
  2. Skip the header with next(f) (or next(reader)), then yield from the reader.
Show a solution
import csv

def parse_data(f_name):
    f = open(f_name)
    try:
        dialect = csv.Sniffer().sniff(f.read(2000))
        f.seek(0)
        next(f)                         # skip the header row
        yield from csv.reader(f, dialect=dialect)
    finally:
        f.close()

Exercise 2: The CSV sink

Write an auto-primed coroutine save_csv(f_name) (a coroutine priming decorator is provided). It opens f_name for writing, and writes each row it receives with csv.writer. When the coroutine is closed, the file must be closed, so all rows are on disk.

Open the file with newline='', as the csv module recommends.

Hints (2)
  1. Decorate the function with @coroutine so it's primed when created.
  2. Open the file with with: close() raises GeneratorExit at the yield, which exits the with block and closes the file.
Show a solution
import csv

def coroutine(fn):
    def inner(*args, **kwargs):
        g = fn(*args, **kwargs)
        next(g)
        return g
    return inner

@coroutine
def save_csv(f_name):
    with open(f_name, 'w', newline='') as f:
        writer = csv.writer(f)
        while True:
            row = yield
            writer.writerow(row)

Exercise 3: Chain any number of name filters

filter_data(pred, target) should forward a row to target only if pred(row) is true, and close target when it is closed itself.

build_chain(target, words) should return the head of a chain of filter_data coroutines, one per word, ending in target. A row reaches target only if every word appears in its first field (row[0]).

The starter's build_chain has the classic closure-in-a-loop bug, and filter_data doesn't pass on close(). Fix both.

Hints (2)
  1. All the lambdas share the single loop variable word. Freeze its current value with a default argument: lambda row, word=word: ....
  2. Wrap filter_data's loop in try/finally and call target.close() in the finally.
Show a solution
def coroutine(fn):
    def inner(*args, **kwargs):
        g = fn(*args, **kwargs)
        next(g)
        return g
    return inner

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

def build_chain(target, words):
    for word in words:
        target = filter_data(lambda row, word=word: word in row[0], target)
    return target

Exercise 4: The context-managed pipeline

Put it all together. parse_data, coroutine, save_csv and filter_data are provided (as in the earlier exercises). Write:

- pipeline_coro(out_file, name_filters): an auto-primed coroutine that builds a chain of name filters ending in save_csv(out_file), forwards every row it receives to the head of that chain, and closes the chain when it is closed; - pipeline(out_file, name_filters): a context manager that creates the pipeline coroutine, gives it to the with block, and always closes it afterwards.

With the filters ('Chevrolet', 'Carlo', 'Landau') the output file must contain exactly the two Chevrolet Monte Carlo Landau rows, comma-separated.

Hints (3)
  1. Start with head = save_csv(out_file), then for each word wrap it: head = filter_data(<predicate>, head). Remember the default-argument trick for the lambda.
  2. In pipeline_coro, put the forwarding loop in try/finally and close head in the finally.
  3. In pipeline, create the coroutine, yield it inside try, and close it in finally.
Show a solution
import csv
from contextlib import contextmanager

def parse_data(f_name):
    f = open(f_name)
    try:
        dialect = csv.Sniffer().sniff(f.read(2000))
        f.seek(0)
        next(f)
        yield from csv.reader(f, dialect=dialect)
    finally:
        f.close()

def coroutine(fn):
    def inner(*args, **kwargs):
        g = fn(*args, **kwargs)
        next(g)
        return g
    return inner

@coroutine
def save_csv(f_name):
    with open(f_name, 'w', newline='') as f:
        writer = csv.writer(f)
        while True:
            writer.writerow((yield))

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

@coroutine
def pipeline_coro(out_file, name_filters):
    head = save_csv(out_file)
    for word in name_filters:
        head = filter_data(lambda row, word=word: word in row[0], head)
    try:
        while True:
            row = yield
            head.send(row)
    finally:
        head.close()

@contextmanager
def pipeline(out_file, name_filters):
    p = pipeline_coro(out_file, name_filters)
    try:
        yield p
    finally:
        p.close()