Context Managers · 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: Temporarily set an attribute ✓ Passed
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__.
class temp_attr:
def __init__(self, obj, name, value):
self.obj = obj
self.name = name
self.value = value
def __enter__(self):
setattr(self.obj, self.name, self.value)
def __exit__(self, exc_type, exc_value, exc_tb):
pass
class Box:
pass
def test_sets_and_returns():
"""sets the attribute inside the block and returns obj"""
b = Box()
b.color = 'red'
with temp_attr(b, 'color', 'blue') as result:
assert result is b, "__enter__ should return obj"
assert b.color == 'blue', f"inside: got {b.color!r}"
def test_restores():
"""restores the previous value"""
b = Box()
b.color = 'red'
with temp_attr(b, 'color', 'blue'):
pass
assert b.color == 'red', f"after: got {b.color!r}"
def test_deletes_new_attribute():
"""deletes an attribute that didn't exist before"""
b = Box()
with temp_attr(b, 'size', 10):
assert b.size == 10
assert not hasattr(b, 'size'), "the attribute should be removed again"
def test_restores_on_error():
"""restores on an exception and lets it propagate"""
b = Box()
b.color = 'red'
try:
with temp_attr(b, 'color', 'blue'):
raise ValueError('boom')
except ValueError:
pass
else:
raise AssertionError("the ValueError was suppressed")
assert b.color == 'red', f"after error: got {b.color!r}"
def test_saves_on_entry():
"""saves the value current at entry, not at creation"""
b = Box()
b.color = 'red'
manager = temp_attr(b, 'color', 'blue')
b.color = 'green'
with manager:
pass
assert b.color == 'green', f"expected 'green', got {b.color!r}"
Hints (2)
getattr(obj, name, default)returnsdefaultwhen the attribute is missing. Use a unique sentinel object (object()) as the default so you can tell "missing" apart fromNone.- Restore with
setattror remove withdelattrin__exit__, and returnFalseso 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 FalseExercise 2: Suppress and record errors ✓ Passed
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')]
from contextlib import contextmanager
@contextmanager
def recording(*exc_types):
errors = []
yield errors
def test_no_error():
"""an empty list when the block succeeds"""
with recording(KeyError) as errors:
x = 1
assert errors == [], f"got {errors}"
def test_records_and_suppresses():
"""a matching exception is recorded and suppressed"""
with recording(KeyError, IndexError) as errors:
[][0]
assert len(errors) == 1, f"expected one recorded error, got {errors}"
assert isinstance(errors[0], IndexError), f"got {errors[0]!r}"
def test_subclass_matches():
"""subclasses of a listed type are recorded too"""
with recording(LookupError) as errors:
{}['k']
assert isinstance(errors[0], KeyError)
def test_other_errors_propagate():
"""non-matching exceptions propagate"""
try:
with recording(KeyError) as errors:
raise ValueError('not mine')
except ValueError as ex:
assert str(ex) == 'not mine'
else:
raise AssertionError("ValueError should not be suppressed")
assert errors == [], "a non-matching error shouldn't be recorded"
def test_rest_of_block_skipped():
"""code after the error inside the block doesn't run"""
ran = []
with recording(ZeroDivisionError):
1 / 0
ran.append('after')
assert ran == []
Hints (3)
- The exception from the block is raised at the
yield. Wrap theyieldintry/except. exceptaccepts a tuple of exception classes, andexc_typesalready is one.- Catching without re-raising tells
contextmanagerto 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 ✓ Passed
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.
import csv
def read_rows(fname):
with open(fname) as f:
return csv.DictReader(f)
import builtins, types
FNAME = 'nyc_parking_tickets_extract.csv'
def test_is_generator():
"""read_rows returns a generator"""
assert isinstance(read_rows(FNAME), types.GeneratorType), "use yield / yield from"
def test_first_row():
"""the first row is a dict keyed by the header"""
row = next(iter(read_rows(FNAME)))
assert isinstance(row, dict), f"got {type(row).__name__}"
assert row['Plate ID'] == 'VAD7274', f"got {row.get('Plate ID')!r}"
def test_all_rows():
"""all 20 data rows are produced"""
rows = list(read_rows(FNAME))
assert len(rows) == 20, f"got {len(rows)} rows"
assert rows[-1]['Vehicle Make'] == 'FORD'
def test_file_closed_after():
"""the file is closed once iteration is finished"""
real_open = builtins.open
opened = []
def tracking_open(*args, **kwargs):
f = real_open(*args, **kwargs)
opened.append(f)
return f
builtins.open = tracking_open
try:
rows = list(read_rows(FNAME))
finally:
builtins.open = real_open
assert opened, "the file was never opened with open()"
assert all(f.closed for f in opened), "a file was left open"
Hints (2)
- Returning the reader leaves the
withblock, which closes the file before any row is read. - Replace
returnwithyield from. The function becomes a generator that stays paused inside thewithuntil 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 ✓ Passed
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.
from contextlib import ExitStack
def zip_files(*names):
result = []
# your code here
return result
import builtins
for i in (1, 2, 3):
with open(f'file{i}.txt', 'w') as f:
f.write('\n'.join(f'file{i}_line{j}' for j in (1, 2, 3)))
with open('short.txt', 'w') as f:
f.write('only one line\n')
def test_three_files():
"""zips three files"""
result = zip_files('file1.txt', 'file2.txt', 'file3.txt')
assert result == ['file1_line1,file2_line1,file3_line1',
'file1_line2,file2_line2,file3_line2',
'file1_line3,file2_line3,file3_line3'], f"got {result}"
def test_one_file():
"""works with a single file"""
assert zip_files('file2.txt') == ['file2_line1', 'file2_line2', 'file2_line3']
def test_shortest():
"""stops at the shortest file"""
result = zip_files('file1.txt', 'short.txt')
assert result == ['file1_line1,only one line'], f"got {result}"
def test_all_closed():
"""every opened file is closed afterwards"""
real_open = builtins.open
opened = []
def tracking_open(*args, **kwargs):
f = real_open(*args, **kwargs)
opened.append(f)
return f
builtins.open = tracking_open
try:
zip_files('file1.txt', 'file2.txt', 'file3.txt', 'short.txt')
finally:
builtins.open = real_open
assert len(opened) == 4, f"expected 4 files to be opened, got {len(opened)}"
assert all(f.closed for f in opened), "a file was left open"
Hints (3)
stack.enter_context(open(name))opens a file, registers it to be closed, and returns the file object.zip(*files)yields one tuple of lines at a time and stops at the shortest file.- Build the full list inside the
withblock (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)]