散列python函数以在修改函数时重新生成输出

Set*_*son 23 python hash caching

我有一个具有确定性结果的python函数.运行并生成大量输出需要很长时间:

def time_consuming_function():
    # lots_of_computing_time to come up with the_result
    return the_result
Run Code Online (Sandbox Code Playgroud)

time_consuming_function不时修改,但我想避免它在没有变化的情况下再次运行.[ time_consuming_function仅取决于为此目的考虑的不可变的功能; 也就是说,它可能有来自Python库的函数,但不能来自我改变的其他代码片段.]向我提出的解决方案是缓存输出并缓存函数的一些"哈希".如果哈希值发生变化,则该函数将被修改,我们必须重新生成输出.

这可能还是荒谬?


更新:基于答案,看起来我想要做的是"memoize" time_consuming_function,除了代替(或除了)传递给不变函数的参数之外,我想要考虑一个本身会改变的函数.

Mik*_*ham 6

如果我理解你的问题,我想我会像这样解决它.这是一个触动的邪恶,但我认为它比我在这里看到的其他解决方案更可靠和更有针对性.

import inspect
import functools
import json

def memoize_zeroadic_function_to_disk(memo_filename):
    def decorator(f):
        try:
            with open(memo_filename, 'r') as fp:
                cache = json.load(fp)
        except IOError:
            # file doesn't exist yet
            cache = {}

        source = inspect.getsource(f)

        @functools.wraps(f)
        def wrapper():
            if source not in cache:
                cache[source] = f()
                with open(memo_filename, 'w') as fp:
                    json.dump(cache, fp)

            return cache[source]
        return wrapper
    return decorator

@memoize_zeroadic_function_to_disk(...SOME PATH HERE...)
def time_consuming_function():
    # lots_of_computing_time to come up with the_result
    return the_result
Run Code Online (Sandbox Code Playgroud)