Home >Backend Development >Python Tutorial >Can Python Decorators Accept Parameters?

Can Python Decorators Accept Parameters?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-20 18:13:18976browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn