Middle
Tell me about decorators in Python: what is this pattern and how to implement a decorator with arguments?
sobes.tech AI
Answer from AI
A decorator in Python is a design pattern that allows you to wrap a function or method, adding additional behavior without modifying the original code.
The simplest decorator is a function that takes another function and returns a new function:
def decorator(func):
def wrapper(*args, **kwargs):
print("Before calling the function")
result = func(*args, **kwargs)
print("After calling the function")
return result
return wrapper
@decorator
def say_hello(name):
print(f"Hello, {name}!")
say_hello("World")
To create a decorator with arguments, an additional level of nesting is needed:
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}!")
greet("Anna")
Here, repeat is a function that takes an argument times and returns a decorator. This approach allows parameterizing the behavior of the decorator.