Python: shortcut for writing decorators which accept arguments?

后端 未结 5 540
闹比i
闹比i 2021-02-06 02:45

Does the Python standard library have a shortcut for writing decorators which accept arguments?

For example, if I want to write a decorator like with_timeout(timeo

5条回答
  •  一生所求
    2021-02-06 03:12

    I know you said it feels suboptimal but I still feel that using three nested models is the cleanest solution. The inner two functions are just the 'normal' way of defining a decorator for a function that takes arguments (see example in python's docs for @wraps). The outer one is really just a function that takes and argument and returns a decorator.

    def with_timeout(timeout):
        def decorator(f):
            @wraps(f)
            def wrapper(*args, **kwargs):
                with Timeout(timeout):
                    return f(*args, **kwargs)
            return wrapper
        return decorator
    

提交回复
热议问题