python decorator模块_Python decorator module
使用functool中的wraps,可以復制一些信息(__name__,__doc__,__module__, __dict__),但是signature還是會被改變(比如參數信息),要保留正確的參數信息,可以使用decorate,從接口上看decorate和update_wrapper相反,這和api的命名就有關了:
update_wrapper wrapper with wrapped.
decorate function with a caller function (the caller function describing the functionality of the decorator).
特別之處在于,decorate方法要求參數中的caller function具備完整的signature
The caller function must have signature (f, *args, **kw), and it must call the original function f with arguments args and kw, implementing the wanted capability (in this case, memoization)
以下面的例子來說,_memoize是caller function,memoize是decorator
def _memoize(func, *args, **kw):if kw: #frozenset is used to ensure hashability
key =args, frozenset(kw.items())else:
key=args
cache= func.cache #attribute added by memoize
if key not incache:
cache[key]= func(*args, **kw)returncache[key]defmemoize(f):"""A simple memoize implementation. It works by adding a .cache dictionary
to the decorated function. The cache will grow indefinitely, so it is
your responsability to clear it, if needed."""f.cache={}returndecorate(f, _memoize)>>>@memoize
...defheavy_computation():
... time.sleep(2)
...return "done"
>>> print(getargspec(heavy_computation))
ArgSpec(args=[], varargs=None, varkw=None, defaults=None)
使用decorator模塊可以防止更改signature,這樣decorator符合一個signature-preserving decorators的要求:
Callable objects which accept a function as input and return a function as output, with the same signature.
來看另外一個例子
def _trace(f, *args, **kw):
kwstr= ','.join('%r: %r' % (k, kw[k]) for k insorted(kw))print("calling %s with args %s, {%s}" % (f.__name__, args, kwstr))return f(*args, **kw)deftrace(f):return decorate(f, _trace)
先了解一下結構:
python中單下劃線開頭代表這是一個內部函數,這里是_trace;
_trace是decorator內部描述裝飾器功能的一個函數,也可以說是wrapper,f是那個wrapped;
與之前的memoize不同,這里的trace只返回內部函數_trace,不聲明其余內容;
所以可以加語法糖!使用@decorator就達到一樣的效果,將一個caller function轉換成一個signature-reserving decorator。
>>>@decorator
...def trace(f, *args, **kw):
... kwstr= ','.join('%r: %r' % (k, kw[k]) for k insorted(kw))
...print("calling %s with args %s, {%s}" % (f.__name__, args, kwstr))
...return f(*args, **kw)
.
總結
以上是生活随笔為你收集整理的python decorator模块_Python decorator module的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AWM狙击步枪是什么
- 下一篇: 美的中央空调售后电话