Context Managers
What you'll build
A Timer context manager (class-based) and a file-processing context manager (decorator-based) that handle setup, teardown, and exceptions.
Goals
- Implement __enter__ and __exit__ methods
- Use contextlib.contextmanager for decorator-based managers
- Handle exceptions in __exit__
- Understand the with statement's guarantees
Prerequisites
- Classes and __init__
- try/finally for cleanup
- The with statement
Steps
- 1
Write a class-based Timer
A context manager class implements __enter__ (setup, returns the resource) and __exit__ (teardown, handles exceptions). Write a Timer that measures the time inside the with block.
Codeimport time class Timer: def __enter__(self): self.start = time.perf_counter() return self def __exit__(self, exc_type, exc_val, exc_tb): 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(1_000_000)) # prints 'Elapsed: 0.0x s'Expected result
After the with block, the elapsed time is printed.
- 2
Handle exceptions in __exit__
If an exception occurs inside the with block, __exit__ receives the exception info. Return True to suppress it, False to propagate. Test both behaviors.
Hint
Returning True from __exit__ swallows the exception — use sparingly, e.g. for expected errors.
- 3
Use contextlib.contextmanager
The @contextmanager decorator turns a generator function into a context manager. yield marks the point where the with block runs. Code before yield is setup; after is teardown.
Codefrom contextlib import contextmanager @contextmanager def open_db(url): print(f"Connecting to {url}") conn = {"url": url, "open": True} # mock connection try: yield conn finally: conn["open"] = False print(f"Closing {url}") with open_db("localhost:5432") as db: print(f"Using {db['url']}, open={db['open']}") # prints: Connecting, Using, ClosingExpected result
Setup runs before the block, teardown runs after (even on exception).
- 4
Nest context managers
You can nest with statements to manage multiple resources. Python 3.10+ allows parentheses for multi-line nesting. Test nested timers and connections.
Hint
ExitStack from contextlib can manage a dynamic number of context managers.
- 5
Build a temporary directory manager
Write a context manager that creates a temp directory, yields its path, and removes it (with all contents) on exit. Use tempfile and shutil for the implementation.
Codeimport tempfile, shutil, os from contextlib import contextmanager @contextmanager def temp_dir(): path = tempfile.mkdtemp() try: yield path finally: shutil.rmtree(path) with temp_dir() as d: print(f"Working in {d}") with open(os.path.join(d, "file.txt"), "w") as f: f.write("hello") # directory and file are now goneExpected result
The temp directory exists inside the block and is removed after.
Try it yourself
class Timer:
def __enter__(self): pass
def __exit__(self, *args): passclass Timer:
def __enter__(self): self.s = time.perf_counter(); return self
def __exit__(self, *a): print(f"{time.perf_counter()-self.s:.4f}s")What you learned
You built context managers — Python's RAII mechanism for resource management. They guarantee cleanup even on exceptions, and are used for files, locks, DB connections, and more.
Related Resources
Related Lessons
- Classes
Class-based context managers use dunder methods.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.