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.

52 lines
1.4 KiB

  1. import pickle
  2. import os
  3. import lzma
  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. def make_key(*args, **kwargs):
  8. return args, tuple(sorted(
  9. kwargs.items(), key=lambda item: item[0]))
  10. class disk_cache:
  11. caches = []
  12. """Decorator to make a function with lru_cache that can be written to disk"""
  13. def __init__(self, func):
  14. self.fname = "{}.{}.dc".format(func.__module__, func.__name__)
  15. self.fname = os.path.join(cache_path, self.fname)
  16. self.func = func
  17. self.load_cache()
  18. disk_cache.caches.append(self)
  19. def __call__(self, *args, **kwargs):
  20. key = make_key(*args, **kwargs)
  21. try:
  22. return self.cache[key]
  23. except KeyError:
  24. res = self.func(*args, **kwargs)
  25. self.cache[key] = res
  26. return res
  27. def load_cache(self):
  28. try:
  29. with lzma.open(self.fname, 'rb') as file:
  30. cache = pickle.load(file)
  31. self.fresh = False
  32. except FileNotFoundError:
  33. cache = {}
  34. self.fresh = True
  35. self.cache = cache
  36. def save_cache(self):
  37. with lzma.open(self.fname, 'wb') as file:
  38. pickle.dump(self.cache, file, pickle.HIGHEST_PROTOCOL)
  39. def delete_cache(self):
  40. os.remove(self.fname)
  41. self.cache = {}
  42. self.fresh = True