SyntaxStudy
Sign Up
Python Decorators with Arguments
Python Intermediate 4 min read

Decorators with Arguments

Decorators with Arguments

To pass arguments to a decorator, add an outer factory function that accepts the arguments and returns the actual decorator.

Example
def repeat(n):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(n):
                func(*args, **kwargs)
        return wrapper
    return decorator

@repeat(3)
def say_hi():
    print("Hi!")

say_hi()  # prints "Hi!" three times
Pro Tip

A decorator with arguments is a three-level nested function.