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

Can Python Decorators Accept Parameters?

Mary-Kate Olsen
Release: 2024-12-20 18:13:18
Original
975 people have browsed it

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
Copy after login

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()
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template