Project 5 · Practice

Quiz & exercises

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

Quiz

1. What is csv.Sniffer().sniff(sample) used for in this project?
2. What does this print?
with open('test.txt', 'w') as f:
    f.write('abcdefghij')

with open('test.txt') as f:
    first = f.read(3)
    second = f.read(3)
    f.seek(0)
    third = f.read(3)
print(first, second, third)
3. What does this print?
from collections import namedtuple

header = ['Car', 'MPG', 'Origin']
Data = namedtuple('Data', map(str.lower, header))
print(Data._fields)
4. A class-based parser opens its file in __enter__, and the next line in __enter__ raises an exception. What happens to the file?
5. What does this print?
from contextlib import contextmanager

@contextmanager
def numbers():
    with open('test.txt', 'w') as f:
        f.write('1\n2\n3\n')
    with open('test.txt') as f:
        yield (int(line) for line in f)

with numbers() as nums:
    print(next(nums))
try:
    print(next(nums))
except ValueError as ex:
    print('ValueError:', ex)
6. Why can't a @contextmanager generator simply yield every data row itself?
from contextlib import contextmanager

@contextmanager
def rows():
    yield 'row 1'
    yield 'row 2'

try:
    with rows() as r:
        print(r)
except RuntimeError as ex:
    print('RuntimeError:', ex)
7. Why does the solution open the file in __enter__ instead of __init__?

Coding exercises

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

Exercise 1: Warm-up: detect the format and read the header

Write read_header(f_name) that returns the file's header row as a list of lowercase field names, whatever the delimiter is. It must:

- open the file only once: sample the first 1000 characters, detect the dialect with csv.Sniffer, rewind with seek(0), then read the header with csv.reader - close the file before returning

For example, read_header('cars.csv') returns ['car', 'mpg', 'cylinders', ...].

Hints (3)
  1. csv.Sniffer().sniff(f.read(1000)) returns a dialect you can pass as the second argument of csv.reader.
  2. After reading the sample, call f.seek(0) so the reader starts at the first line again.
  3. next(reader) gives you the first parsed row: the header.
Show a solution
import csv

def read_header(f_name):
    with open(f_name) as f:
        dialect = csv.Sniffer().sniff(f.read(1000))
        f.seek(0)
        reader = csv.reader(f, dialect)
        return [name.lower() for name in next(reader)]

Exercise 2: Goal 1: a class-based parsing context manager

Write a class FileParser(f_name) that is both a context manager and an iterator:

- __enter__ opens the file, detects its dialect with csv.Sniffer, reads the header row, creates a named tuple class called Data whose fields are the lowercased header names, and returns self - iterating over the object yields each data row, lazily, as a Data named tuple (all values stay strings) - __exit__ closes the file and doesn't suppress exceptions - once the with block has ended, iterating simply stops (no exception)

python with FileParser('cars.csv') as data: print(next(data).car) # Chevrolet Chevelle Malibu

Hints (3)
  1. In __enter__: open the file, sniff a sample with csv.Sniffer().sniff(f.read(1000)), seek(0), create a csv.reader, and consume the header with next(reader).
  2. Build the row type with namedtuple('Data', ...) from the lowercased header names, and store the file, reader and class on self.
  3. __next__ returns self._nt(*next(self._reader)), but first raises StopIteration if the file is already closed.
Show a solution
import csv
from collections import namedtuple

class FileParser:
    def __init__(self, f_name):
        self.f_name = f_name
        self._f = None

    def __enter__(self):
        self._f = open(self.f_name)
        try:
            dialect = csv.Sniffer().sniff(self._f.read(1000))
            self._f.seek(0)
            self._reader = csv.reader(self._f, dialect)
            headers = next(self._reader)
            self._nt = namedtuple('Data', (h.strip().lower() for h in headers))
        except BaseException:
            self._f.close()
            raise
        return self

    def __exit__(self, exc_type, exc_value, exc_tb):
        self._f.close()
        return False

    def __iter__(self):
        return self

    def __next__(self):
        if self._f is None or self._f.closed:
            raise StopIteration
        return self._nt(*next(self._reader))

Exercise 3: Goal 2: a generator-based parsing context manager

Implement the same tool with a generator function decorated with contextlib.contextmanager:

- parsed_data(f_name) opens the file, detects its dialect, reads the header and creates a Data named tuple class with lowercased field names - it yields a lazy iterator (a generator) of Data rows - the file is closed when the with block ends, including when the block raises (and the exception must propagate)

python with parsed_data('personal_info.csv') as data: print(next(data).first_name) # Sebastiano

Hints (3)
  1. The generator must yield exactly once. What you yield is what as binds: make it a generator expression over the reader.
  2. Open the file before a try, put the setup and the yield inside it, and close the file in finally. (Or put everything inside with open(f_name) as f:.)
  3. Use csv.Sniffer().sniff(f.read(1000)) and f.seek(0) to detect the delimiter without reopening the file.
Show a solution
import csv
from collections import namedtuple
from contextlib import contextmanager

@contextmanager
def parsed_data(f_name):
    f = open(f_name)
    try:
        dialect = csv.Sniffer().sniff(f.read(1000))
        f.seek(0)
        reader = csv.reader(f, dialect)
        headers = map(str.lower, next(reader))
        nt = namedtuple('Data', headers)
        yield (nt(*row) for row in reader)
    finally:
        f.close()