Advanced functions and decorators · 4 / 15 Theory

Decorators with parameters

Sometimes you want to customize the decorator: "repeat the function 3 times", "warn only if it takes more than 1 second". For that the decorator needs a parameter, and the trick is to add one more level of functions.

Three levels

def repeat(times):                     # 1. receives the parameter
    def decorator(function):           # 2. receives the function
        def wrapper(*args, **kwargs):      # 3. runs on every call
            for _ in range(times):
                function(*args, **kwargs)
        return wrapper
    return decorator

@repeat(3)
def greet(name):
    print(f"Hello, {name}")

greet("Ana")
# Hello, Ana
# Hello, Ana
# Hello, Ana

When you write @repeat(3), Python does two things: first it calls repeat(3), which returns decorator; then it applies decorator to the function. It is equivalent to:

def say_goodbye(name):
    print(f"Goodbye, {name}")

say_goodbye = repeat(2)(say_goodbye)

say_goodbye("Luis")
# Goodbye, Luis
# Goodbye, Luis

That second form is the one to use when the value of the parameter comes from user input and is not known when writing the code. Practice with Decorator with a parameter.

A decorator that validates the result

Another practical example: making sure a function never returns a negative value. Notice the three levels again:

from functools import wraps

def minimum(min_value):
    def decorator(function):
        @wraps(function)
        def wrapper(*args, **kwargs):
            result = function(*args, **kwargs)
            if result < min_value:
                return min_value
            return result
        return wrapper
    return decorator

@minimum(0)
def subtract(a, b):
    return a - b

print(subtract(10, 3))   # 7
print(subtract(3, 10))   # 0

Applying several decorators

They can be stacked. They are applied from bottom to top: first the one closest to the function:

def uppercase(function):
    def wrapper():
        return function().upper()
    return wrapper

def exclaim(function):
    def wrapper():
        return function() + "!"
    return wrapper

@exclaim
@uppercase
def greeting():
    return "hello"

print(greeting())   # HELLO!

Here greeting is first converted to upper case and then the exclamation mark is added. If you swapped the order, the result would still be HELLO!, but with other decorators the order can matter.

Decorators that already exist

You have already seen some without knowing it: @property, @classmethod and @staticmethod in classes are decorators. In the functools module you have @wraps, @cache and @lru_cache.