What You Will Learn
Intermediate
- What context managers are
- __enter__ and __exit__ methods
- Using contextlib.contextmanager
Terminalpython
# Built-in context manager: file handling
with open("file.txt", "w") as f:
f.write("Hello")
# File is automatically closed, even if error occurs!
# Creating your own context manager
class Timer:
def __enter__(self):
import time
self.start = time.time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
import time
elapsed = time.time() - self.start
print(f"Elapsed: {elapsed:.2f}s")
with Timer():
# Code to time
total = sum(range(1000000))
print(f"Result: {total}")Using contextlib
Terminalpython
from contextlib import contextmanager
import time
@contextmanager
def timer():
start = time.time()
yield # Code inside the with block runs here
elapsed = time.time() - start
print(f"Elapsed: {elapsed:.2f}s")
with timer():
total = sum(range(1000000))Practical Exercise
Use with open() as f - note auto-close
Create a Timer class with __enter__/__exit__
Use it with: with Timer(): ...
Try @contextmanager from contextlib
Key Takeaways
- Context managers: setup + teardown via with statement.
- __enter__: setup (return resource). __exit__: cleanup (always runs).
- with open(): auto-closes file. with lock(): auto-releases.
- contextlib.contextmanager: simpler way to create them.
- Use for: files, database connections, locks, timers.
Comments
Comments
Post a Comment