memoize to disk - python - persistent memoization

前端 未结 9 924
再見小時候
再見小時候 2020-12-24 05:34

Is there a way to memoize the output of a function to disk?

I have a function

def getHtmlOfUrl(url):
    ... # expensive computation
<
9条回答
  •  情深已故
    2020-12-24 06:18

    A cleaner solution powered by Python's Shelve module. The advantage is the cache gets updated in real time via well-known dict syntax, also it's exception proof(no need to handle annoying 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
    

    This will facilitate the function to be computed just once. Next subsequent calls will return the stored result.

提交回复
热议问题