Python Decorators and Generators
Wrap behavior and stream data lazily with yield.
- python decorator
- generator
- yield
- functools.wraps
- contextmanager
Python Decorators and Generators
Wrap behavior and stream data lazily with yield.
Commands
| Command | What it does |
|---|---|
@functools.wraps(fn) | Preserve name/docs in wrappers |
def gen(): yield x | Generator function |
(x*x for x in items) | Generator expression (lazy) |
itertools islice first 5 | Take first 5 lazily |
contextlib contextmanager | Turn a generator into a with-block |
Example
from functools import wraps
def retry(fn):
@wraps(fn)
def wrapper(*a, **k):
for _ in range(3):
try: return fn(*a, **k)
except TimeoutError: pass
return wrapper
FAQ
When are generators worth it?
Large or infinite streams (logs, rows): constant memory instead of materializing full lists.
Decorator with arguments?
A three-level factory: outer takes args, middle takes fn, inner wraps the call.
Perguntas frequentes
When are generators worth it?
Large or infinite streams (logs, rows): constant memory instead of materializing full lists.
Decorator with arguments?
A three-level factory: outer takes args, middle takes fn, inner wraps the call.
Python
Python Venv and Environments
Isolate dependencies per project with venv and pinned requirements.
Python Pip Essentials
Install, upgrade, and audit packages with pip like a pro.
Python Basics
Syntax survival kit: variables, loops, f-strings, and errors.
Python Strings
Slice, split, join, and format text efficiently.