如何存储执行函数的结果并在以后重复使用?

2024-04-19 09:14:39 发布

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

例如,我有:

def readDb():
    # Fetch a lot of data from db, spends a lot time
    ...
    return aList

def calculation():
    x = readdb()
    # Process x
    ...
    return y

在python解释器中,
每次我运行calculation()都需要花费大量时间来重新读取数据库,这是不必要的。
如何存储readdb()的结果以避免这种还原过程?

编辑:
我在这里发现了一个类似的问题,但我不太清楚答案
Save functions for re-using without re-execution


Tags: offromredbdatareturntimedef
3条回答
def readDb():
    ... #Fetch a lot of data from db, spends a lot time
    return aList

def calculation(data):
    x=data
    ...process x...
    return y

data = readDb()

calculation(data)
calculation(data)
calculation(data)

这只会命中数据库一次。

基本上,您希望将readDb()的结果保存到一个单独的变量中,然后可以传递给calculation()。

为现代Python更新了答案

对于仍在搜索如何执行此操作的任何人,标准库functools包含一个装饰函数^{}来执行此操作。

例如(来自文档):

@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

这将存储对32的最后一次get_pep调用,当使用相同参数调用时,将返回缓存值。

写一个简单的装饰:

class memo(object):
    def __init__(self, fun):
        self.fun = fun
        self.res = None
    def __call__(self):
        if self.res is None:
            self.res = self.fun()
        return self.res

@memo
def readDb():
    # ... etc
    return aList

有关更一般的解决方案,请参见:http://code.activestate.com/recipes/498245-lru-and-lfu-cache-decorators/

相关问题 更多 >