Context Managers — Python

A context manager is an object that gives a block of code an opening step and a closing step. with runs the opening step, the block, then the closing step…

Mr. Darto's cash drawer has a spring lock. He opens the drawer to take money. After that, the sale may go well, or there may be a problem with the customer's money. Whatever happens, the drawer locks itself as soon as Mr. Darto takes his hand away. Nobody has to remember to lock it.

Code also has things that must be cleaned up after use, like the drawer that must be locked: a file that has to be closed, or a connection to a database that has to be closed. A context manager is an object that wraps a block of code with two steps: an opening step at the start and a closing step (cleanup) at the end. You write that block under a with line, and with guarantees that the closing step always runs, even when the block fails. In the picture of Mr. Darto's drawer, opening the drawer is the opening step, taking the money is the block of code, and the drawer locking itself is the closing step that with guarantees.

Without with, the cleanup can be skipped

In this code the closing step, print("drawer locked"), is written as an ordinary line at the end:

print("drawer opened")
payment = int("15.00")
print("received", payment)
print("drawer locked")

When you run it:

drawer opened
Traceback (most recent call last):
  File "/home/darto/stall.py", line 2, in <module>
    payment = int("15.00")
ValueError: invalid literal for int() with base 10: '15.00'

int("15.00") on line 2 fails, because the text has a dot in it. That error stops the program, so drawer locked never prints. The drawer is left open. You know the fix from the try-except lesson: put the closing step in finally, which always runs.

print("drawer opened")
try:
    payment = int("15.00")
    print("received", payment)
finally:
    print("drawer locked")

Now drawer locked prints before the traceback. The pattern is: open, try, finally, close. A context manager wraps this pattern into one name, so you don't have to write it again every time.

Making a context manager with @contextmanager

Here is the cash drawer as a context manager, then used with with:

from contextlib import contextmanager

@contextmanager
def cash_drawer():
    print("drawer opened")      # opening step
    try:
        yield                   # the with block runs here
    finally:
        print("drawer locked")  # closing step, always runs

with cash_drawer():
    payment = int("15")
    print("received", payment)
print("stall keeps going")

The order in which it runs:

Step What runs Printed
entering with cash_drawer(): the function up to yield drawer opened
the with block payment = int("15"), then print received 15
the block ends continues after yield, into finally drawer locked
after with the next line stall keeps going

When the block fails

Replace int("15") with int("15.00"), then run it again:

drawer opened
drawer locked
Traceback (most recent call last):
  File "/home/darto/stall.py", line 12, in <module>
    payment = int("15.00")
ValueError: invalid literal for int() with base 10: '15.00'

Without try/finally around yield, the result is different. The error comes out of yield, and the print("drawer locked") line after it never runs:

drawer opened
Traceback (most recent call last):
  File "/home/darto/stall.py", line 10, in <module>
    payment = int("15.00")
ValueError: invalid literal for int() with base 10: '15.00'

The class version: enter and exit

You can also make a context manager from a class, with two special methods:

class CashDrawer:
    def __enter__(self):
        print("drawer opened")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print("drawer locked")
        return False

with CashDrawer():
    payment = int("15.00")
    print("received", payment)
print("stall keeps going")

The output is the same as the @contextmanager version with try/finally: drawer opened, drawer locked, then the ValueError traceback.

with open and nested with

The context manager you will use most is a file: with open("sales.txt", encoding="utf-8") as f:. open() opens the file, and f is that open file. The file is closed automatically as soon as the block ends, even when there is an error. The details are in the next lesson, File I/O.

with blocks can also be nested, which means one with inside another. The last one opened is closed first:

from contextlib import contextmanager

@contextmanager
def section(name):
    print("open", name)
    yield
    print("close", name)

with section("stall"):
    with section("drawer"):
        print("received 15")

The output:

open stall
open drawer
received 15
close drawer
close stall

The block in this example cannot fail, so the yield in that function is safe with no try around it. If the block can fail, wrap yield in try/finally. This lesson's exercise uses the same pattern for HTML tags.

⚠️ Why didn't the drawer lock, or where did the error go?

TL;DR: A context manager is an object that gives a block of code an opening step and a closing step. with runs the opening step, the block, then the closing step. That closing step always runs, even when the block fails. The error still comes out afterwards: with does not swallow errors (it does not make them disappear). The quick way to make a context manager: write @contextmanager from contextlib above a function with one yield. The code before yield is the opening step, and the code after it is the closing step. Wrap yield in try/finally so the closing step still runs on an error. The class version: __enter__ runs when the block starts and its return value goes to the name after as, and __exit__ runs every time the block ends. An __exit__ that returns True swallows the error. Nested with blocks close from the innermost one outwards. with open(...) as f: closes its file automatically.

⚡ Cleanup that can be skipped

Write:

print("drawer opened")
payment = int("15.00")
print("received", payment)
print("drawer locked")
Guess first: is drawer locked printed?

No. int("15.00") on line 2 fails because the text has a dot in it, and that error stops the program. So the drawer is left open.

Meaning: A closing step (cleanup), here print("drawer locked"), can be skipped when it is written as an ordinary line. The fix is finally, which always runs. A context manager wraps that open, try, finally, close pattern into one name.

⚡ Opening, yield, closing

Write:

from contextlib import contextmanager

@contextmanager
def cash_drawer():
    print("drawer opened")      # opening step
    try:
        yield                   # the with block runs here
    finally:
        print("drawer locked")  # closing step, always runs

with cash_drawer():
    payment = int("15")
    print("received", payment)
print("stall keeps going")

Meaning: @contextmanager turns this function into a context manager. The code before yield runs when the with starts, then the with block runs at the yield, and then the code after yield runs. The try/finally around yield makes the closing step run even on an error.

⚡ When the block fails

Guess first: int("15") is changed to int("15.00"). What gets printed: drawer locked, stall keeps going, or both?

Only drawer locked, then a ValueError traceback. The drawer is locked, but the error still comes out and the program stops.

Meaning: with guarantees the closing step always runs, even when there's an exception. But with doesn't swallow the error: the error still comes out, and the program stops.

⚡ with open

Meaning: The context manager you'll use most is a file. with open("sales.txt", encoding="utf-8") as f: opens the file and keeps it in f. The file is closed automatically as soon as the block ends, even when there's an error.

What you will learn