Sobes.tech
Junior — Middle

Is it possible to create a decorator that accepts parameters?

sobes.tech AI

Answer from AI

Yes, in Python, you can create a decorator that accepts parameters. Usually, this involves defining a wrapper function that takes the decorator parameters and returns the actual decorator.

Example of a parameterized decorator:

def repeat(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(times=3)
def say_hello():
    print("Hello")

say_hello()
# Will print "Hello" three times

Here, repeat is a function that takes the parameter times and returns a decorator decorator. This decorator wraps the original function func in wrapper, which calls it the specified number of times.