QuickDevGuide

Home › Python

Decorators & Context Managers — Python

Decorators A decorator is a function that takes a function and returns a new one, adding behaviour around it — logging, timing, caching, retries, access control. @decorator above a definition is shorthand for func = decorator(func). Always use functools.wraps so the wrapped function keeps its name and docstring. A decorator with arguments needs one extra level of nesting. Built-in decorators @property, @classmethod, @staticmethod, @functools.cache / lrucache, @dataclass, @contextmanager. Context managers The with statement guarantees set-up and tear-down, even when an exception occurs — files, locks, database transactions, temporary settings. Write one as a class (enter/exit) or, more simply, as a generator with @contextlib.contextmanager.

Key Takeaways