contextlib
The Python contextlib
module provides utilities for working with context managers, which allows you to allocate and release resources precisely.
This module is especially useful for creating context managers and managing resources in a clean and safe way.
Here’s a quick toy example:
>>> from contextlib import contextmanager
>>> @contextmanager
... def context():
... print("Entering")
... yield
... print("Exiting")
...
>>> with context():
... print("Inside")
...
Entering
Inside
Exiting
Key Features
- Provides utilities for creating context managers
- Facilitates resource management and cleanup
- Offers decorators and helper functions for common context manager patterns
- Supports context manager chaining and nesting
Frequently Used Classes and Functions
Object | Type | Description |
---|---|---|
contextlib.contextmanager |
Decorator | Converts a generator function into a context manager |
contextlib.closing |
Class | Ensures that a resource is closed when done |
contextlib.suppress |
Class | Suppresses specified exceptions |
contextlib.ExitStack |
Class | Allows dynamic management of a stack of context managers |
Examples
Using @contextmanager
to create a function-based context manager:
>>> from contextlib import contextmanager
>>> @contextmanager
... def writable_file():
... try:
... print("Open file for writing...")
... file = open("hello.txt", mode="w", encoding="utf-8")
... yield file
... finally:
... print("Closing file...")
... file.close()
...
>>> with writable_file() as file:
... file.write("Hello, World!")
...
Open file for writing...
13
Closing file...
Note: Using open()
is preferred for files. The example above is for demonstration purposes only.
Automatically closing a file using the closing()
context manager:
>>> from contextlib import closing
>>> from urllib.request import urlopen
>>> with closing(urlopen("http://www.example.com")) as page:
... for line in page:
... print(line)
...
Suppressing specific exceptions with the suppress()
context manager:
>>> from contextlib import suppress
>>> with suppress(FileNotFoundError):
... open("non_existent_file.txt")
...
Common Use Cases
- Creating lightweight context managers without defining a full class
- Managing multiple context managers dynamically
- Ensuring resources are properly cleaned up, such as file handles or network connections
- Suppressing specific exceptions in a clean and controlled manner
Real-World Example
Suppose you want to handle multiple resources that need to be opened and closed. Using ExitStack
, you can manage these resources efficiently:
>>> from contextlib import ExitStack
>>> files = ["file1.txt", "file2.txt"]
>>> with ExitStack() as stack:
... file_objects = [
... stack.enter_context(open(fname, "w")) for fname in files
... ]
... for file in file_objects:
... file.write("Hello, World!")
...
13
13
In this example, ExitStack
allows you to enter and manage multiple context managers, ensuring that they’re all properly closed when the block is exited. This approach facilitates resource management when dealing with multiple context managers.
Related Resources
Tutorial
Context Managers and Python's with Statement
In this step-by-step tutorial, you'll learn what the Python with statement is and how to use it with existing context managers. You'll also learn how to create your own context managers.
For additional information on related topics, take a look at the following resources:
- Reading and Writing Files in Python (Guide) (Tutorial)
- Python Exceptions: An Introduction (Tutorial)
- Context Managers and Using Python's with Statement (Course)
- Context Managers and Python's with Statement (Quiz)
- Reading and Writing Files in Python (Course)
- Reading and Writing Files in Python (Quiz)
- Introduction to Python Exceptions (Course)
- Raising and Handling Python Exceptions (Course)
- Python Exceptions: An Introduction (Quiz)
By Leodanis Pozo Ramos • Updated June 26, 2025