【发布时间】:2018-01-08 21:17:04
【问题描述】:
我有一个函数需要很长时间,并且需要能够缓存它自己的结果,以便在使用相同参数再次调用它时。请参阅下面的示例,该示例似乎可以解决问题。我正在使用 Python 3.6
我的问题围绕着这条线:
param_sig = repr(locals())
1) 是否有更 Pythonic 的方式来获取传递给函数的参数的唯一签名?
2) 我可以依赖 Python 将函数参数插入到 locals() 映射中的顺序吗?同样,这似乎可行,但如果需要,我可以在不太优雅的签名创建者中明确地重新列出每个参数,例如:
param_sig = "{},{},{}".format(a,b,c)
示例代码:
import random
cached_answers = {}
def f(a=1, b=2, c=3):
param_sig = repr(locals())
if param_sig in cached_answers:
ans = cached_answers[param_sig]
print("Call: {} = CACHED {}".format(param_sig,ans))
return ans
else:
# do heavy lifting then cache the result
ans = random.random()
print("Call: {} = {}".format(param_sig,ans))
cached_answers[param_sig] = ans
return ans
# various calls... some of which are repeated and should be cached
f()
f(b=9)
f(c=9, a=9)
f() # should be cached
parms={'a':9}
f(**parms)
f(b=9) # should be cached
f(a=9) # should be cached
【问题讨论】:
-
...为什么不使用
functools.lru_cache?
标签: python python-3.x function parameters