On this page

Context Managers

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Why context managers exist​

Many operations in Python require setup and cleanup.

Examples include:

If cleanup is forgotten or an exception interrupts execution, the program may leak resources or leave the system in an inconsistent state.

Context managers solve this by guaranteeing that cleanup happens every time, even if an error occurs.

How the with statement works​

A context manager is any object that implements two special methods:

When Python executes:


with resource as r:

    use(r)

it performs the following steps:

  1. Calls resource.__enter__() and assigns its return value to r
  2. Executes the block
  3. Calls resource.__exit__(exc_type, exc_value, traceback)

This mechanism ensures that cleanup is always executed.

Understanding the file example​

The most common context manager is file handling:


with open("data.txt", encoding="utf-8") as f:

    content = f.read()

open() returns a file object that implements __enter__() and __exit__().

When the block finishes, the file is closed automatically, even if an exception occurs during reading.

This pattern prevents resource leaks and is the recommended way to work with files.

Creating a custom context manager with a class​

You can implement your own context manager by defining __enter__() and __exit__().

Example: timing a block of code.


import time



class Timer:

    def __enter__(self):

        self.start = time.perf_counter()

        return self



    def __exit__(self, exc_type, exc_value, traceback):

        self.end = time.perf_counter()

        self.elapsed = self.end - self.start

Usage:


with Timer() as t:

    heavy_computation()



print(t.elapsed)

The Timer object measures the duration of the block without requiring manual start/stop calls.

Using contextlib for simpler context managers​

The contextlib module provides tools for writing context managers without creating full classes.

Using @contextmanager​

This decorator allows you to write a context manager as a generator function.


from contextlib import contextmanager



@contextmanager

def temporary_directory(path):

    import os

    os.mkdir(path)

    try:

        yield path

    finally:

        os.rmdir(path)

Usage:


with temporary_directory("temp"):

    process_files()

The code before yield runs at the start, and the code in finally runs at the end.

Using contextlib.ExitStack​

ExitStack is useful when you need to manage a dynamic number of context managers.


from contextlib import ExitStack



with ExitStack() as stack:

    files = [stack.enter_context(open(p)) for p in paths]

    process(files)

This pattern is ideal when the number of resources is not known in advance.

Designing context managers for real‑world tasks​

Context managers are appropriate when:

Common examples include:

Context managers provide a clean, predictable structure for these operations.

Key principles for writing reliable context managers​

Context managers are one of Python’s most powerful tools for writing safe, maintainable, and predictable code, especially in systems that interact with external resources.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Iterators & Custom Iterables

Next

Concurrency with Threads