首页 > 代码库 > Python decorator module

Python decorator module

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