What it is
Context managers are a way to manage resources in Python, such as file handles or database connections. They ensure that resources are properly acquired and released, even if an error occurs during their use.
You can create a context manager using the with statement, which automatically handles the setup and teardown of the resource.
with open('file.txt', 'r') as file:
content = file.read()To implement a class that acts as a context manager, e.g. for managing a database connection, you need to define the __enter__ and __exit__ methods:
class DatabaseConnection:
def __enter__(self):
self.connection = create_database_connection()
return self.connection
def __exit__(self, exc_type, exc_value, traceback):
self.connection.close()Then you can use it like this:
with DatabaseConnection() as conn:
# Use the database connectionTIP
Use context managers whenever you need to ensure proper resource cleanup (files, database connections, locks, etc.). They guarantee cleanup happens even if exceptions occur.