- Courses
- 💻Programming Languages
- 🐍Python
- Advanced Python
- Context Managers
On this page
Context Managers
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Why context managers exist
Many operations in Python require setup and cleanup.
Examples include:
- Opening and closing files
- Acquiring and releasing locks
- Starting and finishing database transactions
- Allocating and freeing network connections
- Temporarily changing settings and restoring them afterward
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:
__enter__()— runs at the start of thewithblock__exit__()— runs at the end of the block, even if an exception occurs
When Python executes:
with resource as r:
use(r)
it performs the following steps:
- Calls
resource.__enter__()and assigns its return value tor - Executes the block
- 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:
- A resource must always be released
- A temporary state must be restored
- A block of code must be wrapped with setup/teardown logic
- You want to guarantee cleanup even if exceptions occur
Common examples include:
- Managing database sessions
- Locking and unlocking threading or multiprocessing locks
- Temporarily changing environment variables
- Redirecting output streams
- Measuring execution time
- Managing temporary files or directories
Context managers provide a clean, predictable structure for these operations.
Key principles for writing reliable context managers
- Always ensure cleanup happens in
__exit__()orfinallyblocks - Keep setup and cleanup logic minimal and focused
- Avoid hiding exceptions unless you explicitly intend to handle them
- Prefer
contextlibwhen the logic is simple - Use class‑based context managers when you need stateful objects
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!
Previous
Iterators & Custom Iterables
Next
Concurrency with Threads
-
Why context managers exist
-
How the with statement works
-
Understanding the file example
-
Creating a custom context manager with a class
-
Using contextlib for simpler context managers
- Using @contextmanager
- Using contextlib.ExitStack
-
Designing context managers for real‑world tasks
-
Key principles for writing reliable context managers
