Python decorator module

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

nuxtServerInit 与 vuex-module-decorators

使用 NuxtJS 和 vuex-module-decorators 的动态 vuex 存储模块

Python decorator

python中的decorator的作用

python之装饰器(decorator)

15-python-decorators