Python:如何存储已执行函数的结果并在以后重用?

MK *_*ung 5 python python-2.7

我有:

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

def calculation():
    x = readdb()
    # Process x
    ...
    return y
Run Code Online (Sandbox Code Playgroud)

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

编辑:
我在这里发现了一个类似的问题,但我不太清楚答案
保存函数重新使用而不重新执行

小智 5

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)
Run Code Online (Sandbox Code Playgroud)

这只会打到数据库一次.

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


djc*_*djc 5

写一个简单的装饰:

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
Run Code Online (Sandbox Code Playgroud)

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