🚪 Context Managers in Python
Context managers allow you to allocate and release resources precisely when you want to. The most widely used example of context managers is the with statement.
🧠 The with Statement
The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.
with open('file.txt', 'w') as f:
f.write('Hello, World!')
This ensures the file is closed properly, even if an error occurs during writing.
🛠 Implementing a Context Manager
You can create your own context managers by defining __enter__ and __exit__ methods in a class.
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, exc_traceback):
self.file.close()
with FileManager('test.txt', 'w') as f:
f.write('Testing context manager')
__enter__: Executed when entering thewithblock. Returns the resource.__exit__: Executed when exiting the block. Handles exceptions if any.
✨ The contextlib Module
Python's contextlib module provides utilities for common tasks involving the with statement.
@contextmanager Decorator
Allows you to define a factory function for with statement context managers, without needing to create a class.
from contextlib import contextmanager
@contextmanager
def open_file(name):
f = open(name, 'w')
try:
yield f
finally:
f.close()
with open_file('test.txt') as f:
f.write('Hello via decorator')
suppress
Suppress specific exceptions.
from contextlib import suppress
import os
with suppress(FileNotFoundError):
os.remove('somefile.tmp')
⚡ Async Context Managers
With asyncio, you can define asynchronous context managers using __aenter__ and __aexit__.
class AsyncContext:
async def __aenter__(self):
await log('entering')
return self
async def __aexit__(self, exc_type, exc, tb):
await log('exiting')
# Usage
# async with AsyncContext() as ctx:
# pass
📝 Summary
- ✅ Resource Management: Automatically handle setup and teardown.
- ✅ Cleaner Code: Replaces
try...finallyblocks. - ✅ Customizable: Create via classes (
__enter__/__exit__) or generators (@contextmanager). - ✅ Versatile: Used for files, locks, database connections, and more.
Created with ❤️ by Pynfinity