You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

34 lines
1005 B

  1. import pickle
  2. import os
  3. import lmza
  4. cache_path = os.path.abspath(os.path.join(__file__, "..", "__pycache__"))
  5. if not os.path.exists(cache_path):
  6. os.mkdir(cache_path)
  7. class disk_cache:
  8. def __init__(self, func):
  9. self.fname = "{}.{}.dc".format(func.__module__, func.__name__)
  10. fname = os.path.join(cache_path, fname)
  11. self.func = func
  12. self.cache = self.load_cache()
  13. def call(self, *args, **kwargs):
  14. key = args + tuple(sorted(self.kwargs.items(), key=lambda item))
  15. try:
  16. return self.cache[key]
  17. except KeyError:
  18. res = self.func(*args, **kwargs)
  19. self.cache[key] = res
  20. def load_cache(self):
  21. try:
  22. with lmza.open(self.fname, 'rb') as file:
  23. cache = pickle.load(file)
  24. except FileNotFoundError:
  25. cache = {}
  26. self.cache = cache
  27. def save_cache(self):
  28. with lmza.open(self.fname, 'wb') as file:
  29. pickle.dump(self.cache, file)