Python: shortcut for writing decorators which accept arguments?

后端 未结 5 541
闹比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:13

    First, we can define a little meta-decorator:

    def decorator_with_arguments(wrapper):
        return lambda *args, **kwargs: lambda func: wrapper(func, *args, **kwargs)
    

    That allows us to create decorators that accept arguments like so:

    @decorator_with_arguments
    def my_wrapper(func, *decorator_args, **decorator_kwargs):
        def wrapped(*call_args, **call_kwargs):
            print "from decorator:", decorator_args, decorator_kwargs
            func(*call_args, **call_kwargs)
        return wrapped
    

    Which can then be used normally:

    @my_wrapper(1, 2, 3)
    def test(*args, **kwargs):
        print "passed directly:", args, kwargs
    
    test(4, 5, 6)
    

    Adding functools.wraps decoration is left as an exercise :)

提交回复
热议问题