Q22: What is a Python Decorator and how does it transform functions?

A decorator is a callable that accepts a function object as an argument and returns a modified wrapper function object. Syntax @decorator is syntactic sugar for fn = decorator(fn).

Writing a Parametrized Decorator
from functools import wraps

def repeat(num_times):
    def decorator(func):
        @wraps(func) # Preserves docstrings and name
        def wrapper(*args, **kwargs):
            for _ in range(num_times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator
💡 Parametrized decorators use three nested function layers to consume arguments.
Key Takeaways
  • Syntactic sugar for function wrapping: fn = decorator(fn).
  • Use functools.wraps to preserve wrapped function metadata (__name__, __doc__).
Knowledge Check

Why should @functools.wraps(func) be applied to wrapper functions inside custom decorators?