Glossary

Context Manager

A context manager is an object that defines actions to be taken when entering and exiting a with statement block. Context managers implement two dunder methods: __enter__() (called when entering the with block, whose return value is bound to the as variable) and __exit__() (called when leaving the block, whether normally or due to an exception). The most common example is file handling: with open('file.txt') as f: ensures the file is closed when the block ends, even if an exception occurs.

Context managers are Python's answer to the resource management problem. They guarantee that cleanup code (closing files, releasing locks, restoring state, committing or rolling back transactions) runs reliably, without relying on the programmer to remember a finally clause. The contextlib module provides utilities for creating context managers: @contextmanager turns a generator function into a context manager, and contextlib.suppress() selectively ignores specified exceptions.

You can stack multiple context managers in a single with statement: with open('a') as f1, open('b') as f2:. Since Python 3.10, parenthesised context managers allow line breaks for readability. Context managers extend far beyond file handling — they are used for database connections, temporary directories, mock patching in tests, decimal precision contexts, and signal handling.

Related terms: Exception, Try/Except

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.