Skip to content

Context Managers

Python

Use context managers (with statement) for resource management.

Official Site
01

Overview

Context managers ensure cleanup with the with statement. __enter__ and __exit__ methods. contextlib.contextmanager for generator-based. Use for files, locks, connections, transactions. Ensures cleanup even on exceptions.

bash
class File:
  def __init__(self,name): self.name=name
  def __enter__(self): self.f=open(self.name); return self.f
  def __exit__(self,*exc): self.f.close()

with File("x.txt") as f: data=f.read()

# contextlib
from contextlib import contextmanager
@contextmanager
def timer():
  import time; start=time.time()
  yield
  print(time.time()-start)
02

Best Practices

Implement __enter__/__exit__ for classes. Use @contextmanager for simple cases. Always use with for files, locks, DB connections. __exit__ receives exception info (suppress by returning True). Use ExitStack for multiple resources.)

Ready to try Context Managers?

Visit the official site for the latest version and full documentation.

Visit Context Managers