首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。