Skip to main content

05. Context Managers in Depth

Context managers simplify resource management (files, network connections, etc.). They ensure proper setup and cleanup.


The with Statement​

with open("example.txt", "w") as f:
f.write("Hello, world!")
# File is automatically closed

How It Works​

A context manager implements two methods:

  • __enter__: Setup
  • __exit__: Cleanup

Creating Your Own Context Manager​

class ManagedResource:
def __enter__(self):
print("Acquiring resource")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Releasing resource")

with ManagedResource():
print("Using resource")

Contextlib Helpers​

from contextlib import contextmanager

@contextmanager
def simple_cm():
print("Start")
yield
print("End")

with simple_cm():
print("Inside")

Practice Challenge​

Write a context manager that measures and prints how long a block of code takes to run.


Wrap-Up​

  • Use with for safe resource management.
  • Create custom context managers with __enter__ and __exit__.
  • Use contextlib.contextmanager for simpler cases.