← All lessons
Python advanced · Lesson 8 of 11

Context managers

with guarantees that something is set up and later cleaned up, whatever happens in between, including an exception. Files are the familiar case, but the same need comes up with locks, database transactions, network connections, temporary folders and timers. An object that works with with is a context manager.

Under the hood, with x as y: calls x.__enter__() at the start and binds what it returns to y, then calls x.__exit__() at the end. __exit__ is told about any exception that's on its way out; returning True from it would swallow the exception, which you almost never want.

class Timer:
    def __enter__(self):
        print("start")
        return self

    def __exit__(self, exc_type, exc, tb):
        print("stop", "with error" if exc_type else "cleanly")
        return False

with Timer():
    print("working")

try:
    with Timer():
        raise ValueError("boom")
except ValueError:
    print("caught outside")
Prints
start
working
stop cleanly
start
stop with error
caught outside

The cleanup ran even though the block blew up, and the exception still reached the outer except. Writing a class is the long way, though. contextlib.contextmanager turns a generator into a context manager: code before the yield is the set-up, the yielded value is what as receives, and code after it (in a finally, so it runs even on errors) is the cleanup.

from contextlib import contextmanager

@contextmanager
def tag(name):
    print(f"<{name}>")
    try:
        yield name
    finally:
        print(f"</{name}>")

with tag("p") as t:
    print("inside", t)
Prints
<p>
inside p
</p>

A few ready-made ones worth knowing: tempfile.TemporaryDirectory() gives a scratch folder that's deleted afterwards, contextlib.suppress(FileNotFoundError) ignores one named exception, threading.Lock() holds a lock for the block, and contextlib.redirect_stdout captures printing. Several can share one with line, separated by commas.

import tempfile, os
from contextlib import suppress
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    p = Path(tmp) / "a.txt"
    p.write_text("hi", encoding="utf-8")
    print(p.exists())
print(p.exists())

with suppress(FileNotFoundError):
    os.remove("no-such-file.txt")
print("carried on")
Prints
True
False
carried on

Whenever you write a pair of calls that must always go together (open and close, lock and unlock, start and stop), make it a context manager. Then nobody, including you, can forget the second half.

Practice

What does this print? (Separate the lines with spaces.)

from contextlib import contextmanager

@contextmanager
def step():
    print("in")
    yield
    print("out")

with step():
    print("body")
More info

Quick reference

with cm as x:Calls cm.__enter__() (result in x), then cm.__exit__() however the block ends.
__exit__(exc_type, exc, tb)Gets the exception, if any; return False to let it carry on.
@contextmanagerA generator: set-up, yield, cleanup in finally.
TemporaryDirectory / suppress / LockBuilt-in context managers for scratch folders, ignoring an error, locking.

Related courses