Middle+
What is a decorator factory?
sobes.tech AI
Answer from AI
A decorator factory is a function that returns a decorator. It takes arguments to configure the behavior of the returned decorator. This allows creating reusable decorators with different behaviors depending on the passed parameters.
# Decorator factory function
def my_decorator_factory(prefix):
# Inner function (decorator) that takes the function to be decorated
def my_decorator(func):
# Another inner function (wrapper) that performs decorator actions
def wrapper(*args, **kwargs):
print(f"{prefix}: Before calling {func.__name__}")
result = func(*args, **kwargs)
print(f"{prefix}: After calling {func.__name__}")
return result
return wrapper
return my_decorator
# Using the factory to create decorators with different prefixes
@my_decorator_factory("DEBUG")
def some_function():
print("Executing some_function")
@my_decorator_factory("INFO")
def another_function(x, y):
print(f"Executing another_function with arguments {x}, {y}")
return x + y
some_function()
result = another_function(5, 10)
print(f"Result: {result}")
Main steps:
- An outer function (factory) is defined with parameters.
- Inside the factory, a decorator function is defined, which takes the function to be decorated.
- Inside the decorator function, a wrapper function is defined, containing the decorator logic and potentially using parameters from the factory and arguments of the decorated function.
- The decorator function returns the wrapper function.
- The factory returns the decorator function.
This is useful for creating flexible and customizable decorators.