Python: shortcut for writing decorators which accept arguments?

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

    I tend to write my decorators as classes to be honest

    class TestWithArgs(object):
        def __init__(self, *deco_args, **deco_kwargs):
            self.deco_args = deco_args
            self.deco_kwargs = deco_kwargs
        def __call__(self, func):
            def _wrap(self, *args, **kwargs):
                print "Blah blah blah"
                return func(*args, **kwargs)
            return _wrap
    

    Its nothing if not slightly clearer

提交回复
热议问题