A context manager in Python is used to safely manage resources like files, network sockets, or database connections. The most common way to use a context manager is with the with statement, which ensures that resources are cleaned up automatically, even if an error occurs inside the block.
Context managers help you write cleaner, safer code by handling common setup/teardown patterns for you.
with statement: Used to wrap the execution of a block with a context manager.__enter__ and __exit__: Special methods that define the behavior of a custom context manager class.contextlib.contextmanager: A decorator that makes it easier to create context managers using a simple function and yield.The basic syntax of the with statement is:
with Syntax
with expression as variable:
# use the resource
... # do something inside context
Under the hood, this works roughly like:
expression must return an object implementing __enter__ and __exit__.__enter__() is called and its result is assigned to variable.with is executed.__exit__() is always called.with with FilesThe most common use of context managers is file handling.
with open("example.txt", "w") as file:
file.write("Hello, World!") # write to file
# File is automatically closed after the block
You can define your own context managers using a class.
class MyContext:
def __enter__(self):
print("Entering the block") # before block
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting the block") # after block
with MyContext() as ctx:
print("Inside the block") # inside
contextlib for Simpler Context ManagersThe contextlib module lets you use generators for context managers.
contextlib Example
from contextlib import contextmanager
@contextmanager
def my_context():
print("Entering") # before block
yield # control passes to caller
print("Exiting") # after block
with my_context():
print("Inside") # inside
If an exception occurs inside a with block, __exit__ (or post-yield code) still runs.
with for resources that must be released.contextmanager decorator for simple cases.__enter__.__exit__ to suppress errors.