Python Context Managers — The with Statement Done Right

Master Python context managers: the with statement, creating custom context managers, and handling resources gracefully.

Python Intermediate 📖 7 min

The with Statement

# File handling with context manager
with open('file.txt', 'w') as f:
    f.write('Hello!')
# File is automatically closed, even if an error occurs

# Database connection
with sqlite3.connect('db.sqlite') as conn:
    conn.execute('CREATE TABLE users (id INTEGER PRIMARY KEY)')

Custom Context Manager with __enter__ and __exit__

class Timer:
    def __enter__(self):
        import time
        self.start = time.perf_counter()
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        import time
        self.elapsed = time.perf_counter() - self.start
        print(f'Elapsed: {self.elapsed:.4f}s')
        return False  # Don't suppress exceptions

with Timer() as t:
    sum(range(1000000))
print(f'Time: {t.elapsed}s')

Contextlib — Easier Way

from contextlib import contextmanager

@contextmanager
def managed_resource(name):
    print(f'Acquiring {name}')
    resource = {'name': name, 'active': True}
    try:
        yield resource
    finally:
        resource['active'] = False
        print(f'Releasing {name}')

with managed_resource('database') as res:
    print(f'Using {res["name"]}')
# Output:
# Acquiring database
# Using database
# Releasing database

Ready to Level Up Your Coding Skills?

Join Coderz Club and learn to code with challenges, battles, and an AI mentor.

Join Coderz Club Free →