Reading history

Python Context Managers: with, __enter__, __exit__ and contextlib

5 min read 1 views

Learn Python context managers: how the with statement works, writing __enter__ and __exit__, @contextmanager generators, suppress and ExitStack.

You have already used with open(...) as f: to make sure a file is closed. That with statement works with any context manager: an object that sets something up when the block starts and cleans it up when the block ends, even if an error happens in between. This lesson shows how with works, how to write your own context managers as a class or with @contextmanager, and the helpers in contextlib.

In this lesson you will learn

  • What the with statement guarantees
  • Writing a context manager class with __enter__ and __exit__
  • How exceptions pass through __exit__
  • Writing one as a generator with @contextmanager
  • contextlib.suppress and ExitStack

The Protocol: __enter__ and __exit__

class Timer:
    def __init__(self, label):
        self.label = label

    def __enter__(self):
        print(f"[{self.label}] start")
        return self                   # bound to the name after "as"

    def __exit__(self, exc_type, exc, tb):
        print(f"[{self.label}] end, error: {exc_type.__name__ if exc_type else None}")
        return False                  # False: let any exception continue

with Timer("load") as t:
    print("working inside", t.label)

try:
    with Timer("parse"):
        int("abc")
except ValueError:
    print("ValueError still reached the caller")

with open("demo.txt", "w") as f:
    f.write("hello")
print("closed after with?", f.closed)
import os; os.remove("demo.txt")

Output

[load] start
working inside load
[load] end, error: None
[parse] start
[parse] end, error: ValueError
ValueError still reached the caller
closed after with? True
  • When the with block starts, Python calls __enter__; its return value is assigned to the name after as.
  • When the block ends, for any reason, Python calls __exit__. It receives the exception type, value and traceback, or three None values if the block finished normally.
  • In the second block, int("abc") raises ValueError; __exit__ still runs and prints the error type. Because it returns False, the exception continues to the surrounding try. Returning True would swallow it, which is rarely what you want.
  • File objects are context managers, which is why the file is closed after the with block, as in File Handling.

@contextmanager and contextlib Helpers

from contextlib import contextmanager, suppress, ExitStack
import os

@contextmanager
def temp_setting(settings, key, value):
    old = settings.get(key)
    settings[key] = value             # code before yield = __enter__
    try:
        yield settings
    finally:
        settings[key] = old           # code after yield = __exit__, always runs

config = {"debug": False}
with temp_setting(config, "debug", True) as c:
    print("inside:", c)
print("after:", config)

with suppress(FileNotFoundError):     # ignore one specific error
    os.remove("does-not-exist.txt")
print("no crash")

names = ["a.txt", "b.txt"]
with ExitStack() as stack:            # manage a variable number of files
    files = [stack.enter_context(open(n, "w")) for n in names]
    for f in files:
        f.write("data")
print([f.closed for f in files])
for n in names:
    os.remove(n)

Output

inside: {'debug': True}
after: {'debug': False}
no crash
[True, True]
  • @contextmanager turns a generator function into a context manager. Code before yield is the setup, the yielded value goes to as, and code after yield is the cleanup.
  • Put the cleanup in finally, otherwise it is skipped when the block raises an exception.
  • suppress(FileNotFoundError) ignores one specific exception type; it is a tidy replacement for try with an empty except.
  • ExitStack manages a number of context managers decided at run time, such as a list of files, and closes all of them at the end.

Where Context Managers Are Used

Context managerSetupCleanup
open(path)Open the fileClose it
threading.Lock()Acquire the lockRelease it
sqlite3.connect(db)Start a transactionCommit, or roll back on error
tempfile.TemporaryDirectory()Create a folderDelete it
unittest.mock.patch(...)Replace an objectRestore the original

Several context managers can share one statement: with open("a") as a, open("b") as b:.

Common Mistakes

  1. Cleanup outside finally in a @contextmanager function, so it is skipped on errors.
  2. Returning True from __exit__ by accident and hiding real errors.
  3. Using the resource after the block, such as reading from a closed file.
  4. Yielding more than once in a @contextmanager generator, which raises RuntimeError.

Practice Exercises

Exercise 1. Write a context manager changed_dir(path) that switches to a folder and switches back afterwards.

Show answer
import os
from contextlib import contextmanager

@contextmanager
def changed_dir(path):
    old = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(old)

Python 3.11 added contextlib.chdir, which does the same thing.

Exercise 2. Use suppress to convert a list of strings to integers, skipping any that are not numbers.

Show answer
from contextlib import suppress
result = []
for s in ["10", "x", "25"]:
    with suppress(ValueError):
        result.append(int(s))
print(result)   # [10, 25]

Frequently Asked Questions

Is with just a shortcut for try/finally?

Essentially, yes. A with block behaves like calling setup, running the body in try, and running cleanup in finally, but the setup and cleanup live in one reusable object.

Are there async context managers?

Yes. Objects with __aenter__ and __aexit__ are used with async with inside async functions, for example for network connections.

Summary

  • with guarantees cleanup when a block ends, even after an error.
  • A class context manager defines __enter__ and __exit__.
  • @contextmanager builds one from a generator; put cleanup in finally.
  • suppress and ExitStack handle common patterns.

Next: Python Unit Testing.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *