Core Python › 7 of 14
Decorators & Context Managers
Wrap behavior: timing, caching, resource cleanup.
python
import time, functools
def timed(fn):
@functools.wraps(fn)
def wrapper(*a, **kw):
t = time.perf_counter()
out = fn(*a, **kw)
print(f"{fn.__name__}: {time.perf_counter()-t:.3f}s")
return out
return wrapper
@functools.lru_cache(maxsize=None)
def embed(text): ...
with open("data.txt") as f:
lines = f.readlines()⚡ Quick check
- ✓ @functools.wraps keeps metadata
- ✓ lru_cache memoizes
- ✓ with closes resources