How to store the result of an executed function and re-use later?

后端 未结 3 1509
悲哀的现实
悲哀的现实 2021-01-19 03:16

E.g., I have:

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

def calculation():
    x = readdb()
    # Process          


        
3条回答
  •  梦毁少年i
    2021-01-19 03:46

    Updated answer for modern Python

    For anyone still searching for how to do this, the standard library functools includes a decorator function @functools.lru_cache to do this.

    For example (from the docs):

    @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'
    

    This would store the last 32 calls to get_pep and when it is called with the same argument, the cached value will be returned.

提交回复
热议问题