记忆到磁盘 \- python - 持久记忆

新手上路,请多包涵

有没有办法将函数的输出记忆到磁盘?

我有一个功能

def getHtmlOfUrl(url):
    ... # expensive computation

并想做类似的事情:

 def getHtmlMemoized(url) = memoizeToFile(getHtmlOfUrl, "file.dat")

然后调用 getHtmlMemoized(url),以便为每个 url 仅执行一次昂贵的计算。

原文由 seguso 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 444
2 个回答

Python 提供了一种非常优雅的方式来做到这一点——装饰器。基本上,装饰器是一个函数,它包装另一个函数以在不更改函数源代码的情况下提供额外的功能。你的装饰器可以这样写:

 import json

def persist_to_file(file_name):

    def decorator(original_func):

        try:
            cache = json.load(open(file_name, 'r'))
        except (IOError, ValueError):
            cache = {}

        def new_func(param):
            if param not in cache:
                cache[param] = original_func(param)
                json.dump(cache, open(file_name, 'w'))
            return cache[param]

        return new_func

    return decorator

完成后,使用@-syntax 来“装饰”函数,就可以了。

 @persist_to_file('cache.dat')
def html_of_url(url):
    your function code...

请注意,此装饰器是有意简化的,可能不适用于所有情况,例如,当源函数接受或返回无法进行 json 序列化的数据时。

有关装饰器的更多信息: How to make a chain of function decorators?

以下是如何让装饰器在退出时只保存缓存一次:

 import json, atexit

def persist_to_file(file_name):

    try:
        cache = json.load(open(file_name, 'r'))
    except (IOError, ValueError):
        cache = {}

    atexit.register(lambda: json.dump(cache, open(file_name, 'w')))

    def decorator(func):
        def new_func(param):
            if param not in cache:
                cache[param] = func(param)
            return cache[param]
        return new_func

    return decorator

原文由 georg 发布,翻译遵循 CC BY-SA 3.0 许可协议

查看 joblib.Memory 。它是一个用于执行此操作的库。

 from joblib import Memory
memory = Memory("cachedir")
@memory.cache
def f(x):
    print('Running f(%s)' % x)
    return x

原文由 Will 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏