【发布时间】:2016-08-14 18:55:24
【问题描述】:
我想做一个 python 装饰器来记忆函数。例如,如果
@memoization_decorator
def add(a, b, negative=False):
print "Computing"
return (a + b) * (1 if negative is False else -1)
add(1, 2)
add(1, b=2)
add(1, 2, negative=False)
add(1, b=2, negative=False)
add(a=1, b=2, negative=False)
add(a=1, b=2)
我希望输出是
Computing
3
3
3
3
3
3
在最后 6 行的任何排列下,输出应该是相同的。
这相当于找到一个映射,将等效的*args, **kwargs** 集合发送到记忆缓存dict 的唯一键。上面的例子有 *args, **kwargs 等于
(1, 2), {}
(1,), {'b': 2}
(1, 2), {'negative': False}
(1,), {'b': 2, 'negative': False}
(), {'a': 1, 'b': 2, 'negative': False}
(), {'a': 1, 'b': 2}
【问题讨论】:
标签: python caching memoization