Context Managers · Practice

Quiz & exercises

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

Quiz

1. What does this print?
class CM:
    def __enter__(self):
        print('enter')
        return self
    def __exit__(self, exc_type, exc_value, tb):
        print('exit', exc_type.__name__)
        return True

with CM():
    raise KeyError('k')
    print('after raise')
print('done')
2. When the with block finishes without an exception, what does __exit__ receive as its three exception arguments?
3. What does this print?
with open('test.txt', 'w') as f:
    x = 'inside'
print(x, f.closed)
4. What does this print?
def lines():
    with open('test.txt', 'w') as f:
        f.write('a\nb\n')
    with open('test.txt') as f:
        return map(str.strip, f)

try:
    print(list(lines()))
except ValueError as ex:
    print('ValueError:', ex)
5. What does this print?
class CM:
    def __enter__(self):
        print('enter')
        raise RuntimeError('setup failed')
    def __exit__(self, *exc):
        print('exit')

try:
    with CM():
        print('body')
except RuntimeError as ex:
    print('caught:', ex)
6. In what order are the messages printed?
class Named:
    def __init__(self, name):
        self.name = name
    def __enter__(self):
        print('enter', self.name)
    def __exit__(self, *exc):
        print('exit', self.name)

with Named('a'), Named('b'):
    print('body')
7. What does this print?
from contextlib import contextmanager

@contextmanager
def cm():
    print('setup')
    yield
    print('cleanup')

try:
    with cm():
        1 / 0
except ZeroDivisionError:
    print('error')
8. What does this print?
from contextlib import contextmanager

@contextmanager
def cm():
    try:
        yield 'value'
    except ValueError as ex:
        print('handled', ex)

with cm() as v:
    raise ValueError(v)
print('after')
9. What does this print?
from contextlib import suppress

with suppress(KeyError):
    print(1)
    {}['missing']
    print(2)
print(3)
10. In what order do these callbacks run?
from contextlib import ExitStack

with ExitStack() as stack:
    for name in 'abc':
        stack.callback(print, name)
    print('body')
11. You need to open a number of files that's only known at run time (every name in a list) and guarantee all of them get closed. What's the best tool?
12. Which statement about __exit__ returning None (no return statement) is true?

Coding exercises

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

Exercise 1: Temporarily set an attribute

Write a class temp_attr(obj, name, value) that works as a context manager:

- on entry, it sets obj.<name> to value and returns obj - on exit, it restores the attribute's previous value, or deletes the attribute if it didn't exist before - restoring must happen even if the block raises, and the exception must not be suppressed

Save the old state on entry, not in __init__.

Hints (2)
  1. getattr(obj, name, default) returns default when the attribute is missing. Use a unique sentinel object (object()) as the default so you can tell "missing" apart from None.
  2. Restore with setattr or remove with delattr in __exit__, and return False so exceptions propagate.
Show a solution
class temp_attr:
    _missing = object()

    def __init__(self, obj, name, value):
        self.obj = obj
        self.name = name
        self.value = value

    def __enter__(self):
        self.saved = getattr(self.obj, self.name, self._missing)
        setattr(self.obj, self.name, self.value)
        return self.obj

    def __exit__(self, exc_type, exc_value, exc_tb):
        if self.saved is self._missing:
            delattr(self.obj, self.name)
        else:
            setattr(self.obj, self.name, self.saved)
        return False

Exercise 2: Suppress and record errors

Using contextlib.contextmanager, write recording(*exc_types). It yields a list. If the block raises an exception that is an instance of one of exc_types, the exception is appended to the list and suppressed. Any other exception must propagate unchanged. If the block succeeds, the list stays empty.

python with recording(KeyError, IndexError) as errors: [][0] print(errors) # [IndexError('list index out of range')]

Hints (3)
  1. The exception from the block is raised at the yield. Wrap the yield in try/except.
  2. except accepts a tuple of exception classes, and exc_types already is one.
  3. Catching without re-raising tells contextmanager to suppress the exception; anything you don't catch propagates.
Show a solution
from contextlib import contextmanager

@contextmanager
def recording(*exc_types):
    errors = []
    try:
        yield errors
    except exc_types as ex:
        errors.append(ex)

Exercise 3: Lazy rows that keep the file open

This function is supposed to return the rows of a CSV file lazily, as dictionaries keyed by the header row, but it fails with ValueError: I/O operation on closed file. as soon as you iterate over the result.

Fix read_rows(fname) so that it is a generator, keeps the file open while rows are being consumed, and closes it once iteration is finished. Test it on nyc_parking_tickets_extract.csv.

Hints (2)
  1. Returning the reader leaves the with block, which closes the file before any row is read.
  2. Replace return with yield from. The function becomes a generator that stays paused inside the with until the rows run out.
Show a solution
import csv

def read_rows(fname):
    with open(fname) as f:
        yield from csv.DictReader(f)

Exercise 4: Zip any number of files

Write zip_files(*names) that opens every file in names, and returns a list of strings, one per line position: the stripped lines of each file joined by commas. Stop at the shortest file (like zip). All files must be closed when the function returns, and the function must work for any number of files.

Use contextlib.ExitStack. The sample files file1.txt, file2.txt and file3.txt from the lesson are created for you by the tests.

Hints (3)
  1. stack.enter_context(open(name)) opens a file, registers it to be closed, and returns the file object.
  2. zip(*files) yields one tuple of lines at a time and stops at the shortest file.
  3. Build the full list inside the with block (a list comprehension, not a lazy generator expression), so the files are still open while you read them.
Show a solution
from contextlib import ExitStack

def zip_files(*names):
    with ExitStack() as stack:
        files = [stack.enter_context(open(name)) for name in names]
        return [','.join(line.strip('\n') for line in lines)
                for lines in zip(*files)]