github.com/pdaian/flashboys2@v0.0.0-20190718175736-b101c35361f0/persistence.py (about)

     1  # https://stackoverflow.com/questions/16463582/memoize-to-disk-python-persistent-memoization
     2  
     3  import json
     4  
     5  def persist_to_file(file_name):
     6  
     7      def decorator(original_func):
     8  
     9          try:
    10              cache = json.load(open(file_name, 'r'))
    11          except (IOError, ValueError):
    12              cache = {}
    13  
    14          def new_func(param):
    15              if param not in cache:
    16                  cache[param] = original_func(param)
    17                  json.dump(cache, open(file_name, 'w'))
    18              return cache[param]
    19  
    20          return new_func
    21  
    22      return decorator