Home >Backend Development >Python Tutorial >Can Python Decorators Accept Parameters?
Can Decorators Take Parameters?
The code attempts to use a decorator (@execute_complete_reservation) with an argument (insurance_mode), but it fails. This happens because decorators with parameters have a different syntax.
Revised Decorator Syntax:
Decorators with parameters return functions that take a function as an argument, and then return another function. It essentially returns a normal decorator.
def decorator_factory(argument): def decorator(function): def wrapper(*args, **kwargs): # Additional code function(*args, **kwargs) # More additional code return wrapper return decorator
Applying the Decorator:
Using this syntax, the original code can be revised as follows:
@execute_complete_reservation_factory(True) def test_booking_gta_object(self): self.test_select_gta_object()
In this revised code, @execute_complete_reservation_factory is a factory function that returns a decorator that takes the actual test function as an argument.
The above is the detailed content of Can Python Decorators Accept Parameters?. For more information, please follow other related articles on the PHP Chinese website!