Ad – 728Γ—90
πŸš€ Advanced Python

Python Context Managers – with Statement and __enter__/__exit__

Context managers handle setup and teardown of resources automatically β€” files, database connections, locks, network sockets. The with statement guarantees that cleanup code always runs, even if an exception occurs. This eliminates a whole class of resource-leak bugs.

⏱️ 20 min read🎯 AdvancedπŸ“… Updated 2026

The with Statement

with ensures the resource is properly closed/released regardless of what happens.

Python
# Without context manager (bad β€” file may not close on error)
f = open("data.txt", "w")
f.write("Hello")  # If this crashes, f.close() never runs!
f.close()

# With context manager (correct)
with open("data.txt", "w") as f:
    f.write("Hello")  # __exit__ calls f.close() automatically
# File is closed here β€” always
πŸ’‘
Tip

Always use with for file operations. It is safer and more readable than manual open/close.

The Context Manager Protocol

Any class with __enter__ and __exit__ works as a context manager.

Python
class Timer:
    import time as _time

    def __enter__(self):
        import time
        self.start = time.time()
        return self   # Bound to "as" variable

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

with Timer() as t:
    total = sum(range(1_000_000))
β–Ά Output
Elapsed: 0.0412s

contextlib.contextmanager – Generator Approach

Use @contextmanager to write context managers as generator functions β€” less boilerplate.

Python
from contextlib import contextmanager

@contextmanager
def managed_resource(name):
    print(f"Opening {name}")
    try:
        yield name      # Everything before yield = __enter__
    finally:
        print(f"Closing {name}")  # Always runs = __exit__

with managed_resource("database") as r:
    print(f"Working with {r}")
β–Ά Output
Opening database Working with database Closing database
Ad – 336Γ—280

Multiple Context Managers

Combine multiple managers in one with statement.

Python
# Open two files simultaneously
with open("input.txt", "r") as src, open("output.txt", "w") as dst:
    for line in src:
        dst.write(line.upper())

# Both files auto-closed after block

contextlib.suppress – Ignore Specific Exceptions

Cleanly suppress known safe exceptions without try/except.

Python
from contextlib import suppress
import os

# Instead of:
try:
    os.remove("temp.txt")
except FileNotFoundError:
    pass

# Use suppress:
with suppress(FileNotFoundError):
    os.remove("temp.txt")