Python: shortcut for writing decorators which accept arguments?

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

    Based on Jakob's suggestion, I've implemented a small Decorator class, which I feel does a fairly decent job:

    class Decorator(object):
        def __call__(self, f):
            self.f = f
            return functools.wraps(f)(lambda *a, **kw: self.wrap(*a, **kw))
    
        def wrap(self, *args, **kwrags):
            raise NotImplemented("Subclasses of Decorator must implement 'wrap'")
    
    class with_timeout(Decorator):
        def __init__(self, timeout):
            self.timeout = timeout
    
        def wrap(self, *args, **kwargs):
            with Timeout(timeout):
                return self.f(*args, **kwargs)
    

提交回复
热议问题