TExcelTAD
Home › Python › Python Context Managers

Python Context Managers

A context manager sets something up, lets your code use it, and then reliably tears it down — even if an error happens in between. You use one every time you write with open(...) as f:. The with statement guarantees the clean-up step runs.

Why with?

Without with, you'd need try/finally to be safe:

python
f = open("data.txt", encoding="utf-8")
try:
    data = f.read()
finally:
    f.close()          # runs even if read() fails

With a context manager, the same guarantee takes one line:

python
with open("data.txt", encoding="utf-8") as f:
    data = f.read()
# f is closed here, no matter what happened

Common context managers in the standard library:

Context manager Sets up / tears down
open(...) opens / closes a file
threading.Lock() acquires / releases a lock
decimal.localcontext() changes / restores decimal precision
contextlib.suppress(...) ignores chosen exceptions
contextlib.redirect_stdout(...) captures print output
tempfile.TemporaryDirectory() creates / deletes a temp folder

Writing a class-based context manager

Any object with __enter__ and __exit__ methods works with with:

  • __enter__(self) runs at the start; its return value is bound to the name after as.
  • __exit__(self, exc_type, exc, tb) runs at the end. If an exception occurred, the three arguments describe it; otherwise they're all None.
python · try it yourself
class Section:
    def __init__(self, title):
        self.title = title

    def __enter__(self):
        print(f"=== {self.title} ===")
        return self

    def __exit__(self, exc_type, exc, tb):
        status = "ok" if exc_type is None else f"failed: {exc}"
        print(f"=== end {self.title} ({status}) ===")
        return False          # don't swallow exceptions

with Section("Setup"):
    print("installing...")

try:
    with Section("Deploy"):
        print("uploading...")
        raise RuntimeError("server unreachable")
except RuntimeError:
    print("handled outside the with block")
=== Setup ===
installing...
=== end Setup (ok) ===
=== Deploy ===
uploading...
=== end Deploy (failed: server unreachable) ===
handled outside the with block

If __exit__ returns True, the exception is suppressed. Returning False (or None) lets it propagate, which is almost always what you want.

The easy way: @contextmanager

The contextlib.contextmanager decorator turns a generator into a context manager. Code before yield is the setup, the yielded value is what as receives, and code after yield is the teardown. Wrap the yield in try/finally so teardown runs even on errors:

python · try it yourself
from contextlib import contextmanager

@contextmanager
def temporary_setting(settings, key, value):
    old = settings[key]
    settings[key] = value
    try:
        yield settings
    finally:
        settings[key] = old

config = {"debug": False, "level": 1}
with temporary_setting(config, "debug", True) as c:
    print("inside:", c)
print("after: ", config)
inside: {'debug': True, 'level': 1}
after:  {'debug': False, 'level': 1}

A file example with clean-up

Here a context manager creates a scratch file and guarantees it's deleted afterwards (in the browser this uses Pyodide's in-memory file system; on your computer it creates exceltad_demo.txt in the current folder and removes it):

python · try it yourself
import os
from contextlib import contextmanager

@contextmanager
def scratch_file(name):
    with open(name, "w", encoding="utf-8") as f:
        f.write("temporary data\n")
    try:
        yield name
    finally:
        os.remove(name)
        print("cleaned up", name)

with scratch_file("exceltad_demo.txt") as path:
    with open(path, encoding="utf-8") as f:
        print("read:", f.read().strip())
    print("exists inside?", os.path.exists(path))

print("exists after? ", os.path.exists("exceltad_demo.txt"))
read: temporary data
exists inside? True
cleaned up exceltad_demo.txt
exists after?  False

Handy tools from contextlib

python · try it yourself
import io
from contextlib import suppress, redirect_stdout

with suppress(KeyError):
    del {}["missing"]          # error silently ignored
print("still running")

buffer = io.StringIO()
with redirect_stdout(buffer):
    print("captured text")
print("buffer holds:", repr(buffer.getvalue()))
still running
buffer holds: 'captured text\n'

Multiple context managers

One with can manage several resources; they're exited in reverse order:

python
with open("input.txt", encoding="utf-8") as src, open("output.txt", "w", encoding="utf-8") as dst:
    dst.write(src.read().upper())

Tip: Whenever you write code that must "always undo" something — close, release, restore, delete — consider packaging it as a context manager.

Test yourself

Which two methods make a class usable in a with statement?

  1. __open__ and __close__
  2. __enter__ and __exit__
  3. __start__ and __stop__
  4. __init__ and __del__

In a @contextmanager generator, what does the code after yield do?

  1. Runs before the with-block
  2. Runs as the clean-up when the with-block ends
  3. Never runs
  4. Runs only on errors

What happens if __exit__ returns True?

  1. The with-block is repeated
  2. The exception (if any) is suppressed
  3. The file is deleted
  4. Nothing special