Glossary

Decorator

A decorator is a callable that takes a function (or class) as input and returns a modified version of it. Decorators are applied using the @ syntax placed above a function definition: @my_decorator followed by def func(): is equivalent to func = my_decorator(func). Decorators are one of Python's most elegant and powerful features, enabling separation of concerns without modifying the original function's code.

Common uses for decorators include logging, timing, access control, caching, and retry logic. The standard library provides several built-in decorators: @staticmethod and @classmethod modify method binding, @property creates managed attributes, @functools.lru_cache adds memoisation, and @functools.wraps preserves the wrapped function's metadata (name, docstring, signature).

Decorators that accept arguments require an extra level of nesting — a decorator factory that returns the actual decorator. For example, @retry(max_attempts=3) calls retry(max_attempts=3), which returns a decorator that wraps the function. Decorators can be stacked: applying multiple @ lines applies them bottom-to-top. Understanding decorators requires comfort with closures and higher-order functions, as a decorator is essentially a closure that wraps a function reference.

Related terms: Closure, Function, functools.wraps, Property

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.