Python, properly · Chapter 32 of 42
Context managers
By the end of this chapter you can explain what with does step by step, write your own context managers as a class and with contextlib.contextmanager, and make cleanup happen even when the code inside fails. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Pythonic and typed
- 4 tasks
- Python
- In the all labs plan
The first 2 chapters of Python, properly are free. This one comes with the all labs plan.
Why you need this
Bhavna's export script moves into a folder, writes files, and is supposed to move back. Last week it crashed halfway and left everything after it writing into the wrong place. Rafiq adds ledger entries in groups, and a crash in the middle of a group left half of it saved.
Both are the same problem: "set something up, do the work, always undo it". You have met the answer already: with open(...) closes the file whatever happens (chapter 17). Today you see how it works, and build your own for folders, timers and all-or-nothing ledgers. Database transactions (chapter 40) and HTTP clients (chapter 37) work the same way.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
timer.py: a Timer for with blocks
Write a class Timer that works with with: in with Timer() as t, the name t gets the Timer itself, and when the block ends the Timer's elapsed attribute holds how long the block took, in seconds (a float).
The check sleeps 0.05 s inside a block. It also raises a KeyError inside a block: elapsed must still be set, and the KeyError must still come out of the with.
- Task 2
in_folder.py: work in a folder, then come back
Write in_folder(path) with contextlib.contextmanager. Inside the with block the current folder is path; after the block the current folder is back to what it was before, even when the block raised, and the block's error still comes out.
os.getcwd() gives the current folder and os.chdir(path) changes it. The check runs one block that works and one that raises ValueError.
- Task 3
ledger.py: all or nothing
Complete the class Ledger. A new ledger's entries is an empty list, and add(entry) appends one entry. transaction() is a context manager: entries added inside the with block stay if the block finishes, but if the block raises, every entry added inside that block is removed (the earlier ones stay) and the error goes on out of the with.
The check adds an opening entry, runs a transaction that works, one that raises ValueError after adding two entries, and an empty one.
- Task 4 · interview question
Interview: ignore.py, your own suppress
Write ignore(*exc_types), a context manager that swallows the exception types it is given (and their subclasses) when they happen inside the with block, and lets any other exception through. Do not use contextlib.suppress.
In with ignore(KeyError), looking up a missing key does nothing and the rest of the block is skipped; int of Rs 240 raises a ValueError that comes out. ignore(LookupError) also swallows an IndexError, a subclass.
What you will learn
- What with does: __enter__, the block, __exit__, in that order, even after an error.
- Writing one as a class, and what __exit__'s return value means.
- contextlib.contextmanager: a context manager from a generator, and its try/finally trap.
- Ready-made ones: suppress, redirect_stdout, several in one with.
More in Pythonic and typed
Build "Context managers" yourself
DabbaDrop, a Mumbai tiffin startup, runs on Excel and WhatsApp. You are its first Python developer. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of Python, properly are free. This one comes with the all labs plan.