memoize to disk-python-持久的memoization

2024-05-13 08:24:06 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法把函数的输出记录到磁盘上?

我有个功能

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

想做点什么:

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

然后调用gethtmlemoized(url),以便对每个url只进行一次昂贵的计算。


Tags: 函数功能urldef记录磁盘datfile
3条回答

Python提供了一种非常优雅的方法来完成这个任务-decorators。基本上,decorator是在不更改函数源代码的情况下包装另一个函数以提供附加功能的函数。你的装潢师可以这样写:

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

一旦你得到了它,就可以用@语法“修饰”函数了。

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

请注意,这个decorator是故意简化的,可能不适用于每种情况,例如,当源函数接受或返回无法进行json序列化的数据时。

关于decorators的更多信息:How to make a chain of function decorators?

下面是如何使decorator在退出时仅保存一次缓存:

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

一个由Python的Shelve模块驱动的更干净的解决方案。其优点是缓存通过众所周知的dict语法实时更新,而且它还具有异常证明(无需处理烦人的KeyError)。

import shelve
def shelve_it(file_name):
    d = shelve.open(file_name)

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

        return new_func

    return decorator

@shelve_it('cache.shelve')
def expensive_funcion(param):
    pass

这将有助于只计算一次函数。接下来的调用将返回存储的结果。

签出^{}。这是一个专门做这些的图书馆。

相关问题 更多 >