我已经有了一个很好用的回忆录。它使用pickle转储序列化输入并创建MD5散列作为键。函数结果非常大,存储为pickle文件,文件名为MD5 hash。当我一个接一个地调用两个记忆化函数时,memoizer
将加载第一个函数的输出并将其传递给第二个函数。第二个函数将序列化它,创建MD5,然后加载输出。下面是一个非常简单的代码:
@memoize
def f(x):
...
return y
@memoize
def g(x):
...
return y
y1 = f(x1)
y2 = g(y1)
当对f
求值时,y1
从磁盘加载,然后在计算g
时序列化它。有没有可能绕过这个步骤,把y1
(即MD5散列)的密钥传递给g
?如果g
已经有这个密钥,它将从磁盘加载y2
。如果没有,它将“请求”完整的y1
来评估{
编辑:
^{pr2}$
我认为你可以用一种自动的方式来做,但我通常认为最好是明确地说明“懒惰”的评价。因此,我将介绍一种向你的记忆化函数添加额外参数的方法:
lazy
。但我将简化助手,而不是文件、pickle和md5:我使用自定义类作为中间对象:
^{pr2}$最后,我展示了更改后的
Memoize
,假设您的函数只接受一个参数:现在,如果调用函数并在正确的位置指定lazy,则可以避免加载(取消拾取)文件:
正常(首次)运行:
没有
lazy
:使用
lazy=True
最后一个选项只计算第一个参数的“md5”,并加载最终结果的文件。那应该正是你想要的。在
相关问题 更多 >
编程相关推荐