Decorators with parameters?

前端 未结 13 1597
我在风中等你
我在风中等你 2020-11-21 22:58

I have a problem with the transfer of variable \'insurance_mode\' by the decorator. I would do it by the following decorator statement:

@execute_complete_rese         


        
13条回答
  •  孤城傲影
    2020-11-21 23:15

    Here is a slightly modified version of t.dubrownik's answer. Why?

    1. As a general template, you should return the return value from the original function.
    2. This changes the name of the function, which could affect other decorators / code.

    So use @functools.wraps():

    from functools import wraps
    
    def decorator(argument):
        def real_decorator(function):
            @wraps(function)
            def wrapper(*args, **kwargs):
                funny_stuff()
                something_with_argument(argument)
                retval = function(*args, **kwargs)
                more_funny_stuff()
                return retval
            return wrapper
        return real_decorator
    

提交回复
热议问题