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

CommandWhat it does
@functools.wraps(fn)Preserve name/docs in wrappers
def gen(): yield xGenerator function
(x*x for x in items)Generator expression (lazy)
itertools islice first 5Take first 5 lazily
contextlib contextmanagerTurn 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.

常见问题

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