码迷,mamicode.com
首页 > 编程语言 > 详细

Python decorator module

时间:2017-05-13 12:27:02      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:tor   init   style   sig   items   abi   href   res   decorator   

Python functool

Python中的装饰器

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 in cache:
        cache[key] = func(*args, **kw)
    return cache[key]

def memoize(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 = {}
    return decorate(f, _memoize)

>>> @memoize
... def heavy_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.

Python decorator module

标签:tor   init   style   sig   items   abi   href   res   decorator   

原文地址:http://www.cnblogs.com/autoria/p/6848466.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!