Glossary

Decorators with Arguments

A decorator with arguments is a decorator that accepts parameters, requiring an additional level of function nesting. When you write @retry(max_attempts=3), Python calls retry(max_attempts=3) first, which returns the actual decorator, which then wraps the function. This means a decorator factory is a function that returns a decorator, which is itself a function that returns a wrapper.

The typical structure has three nested layers: the outer function receives the decorator's arguments, the middle function receives the decorated function, and the inner function (the wrapper) replaces the original. For example: def retry(max_attempts): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): ... return wrapper; return decorator.

This triple nesting can be confusing. Some developers use a class-based approach instead: a class whose __init__ accepts the arguments and whose __call__ method wraps the function. The functools.wraps decorator should be applied to the innermost wrapper to preserve the original function's metadata. Understanding decorators with arguments is a milestone in Python fluency — it exercises closures, higher-order functions, and the decorator protocol all at once.

Related terms: Decorator, Closure, functools.wraps

Discussed in:

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