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.

48 lines
1.3 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. def __init__(self, func):
  12. self.fname = "{}.{}.dc".format(func.__module__, func.__name__)
  13. self.fname = os.path.join(cache_path, self.fname)
  14. self.func = func
  15. self.load_cache()
  16. def __call__(self, *args, **kwargs):
  17. key = make_key(*args, **kwargs)
  18. try:
  19. return self.cache[key]
  20. except KeyError:
  21. res = self.func(*args, **kwargs)
  22. self.cache[key] = res
  23. return res
  24. def load_cache(self):
  25. try:
  26. with lzma.open(self.fname, 'rb') as file:
  27. cache = pickle.load(file)
  28. self.fresh = False
  29. except FileNotFoundError:
  30. cache = {}
  31. self.fresh = True
  32. self.cache = cache
  33. def save_cache(self):
  34. with lzma.open(self.fname, 'wb') as file:
  35. pickle.dump(self.cache, file)
  36. def delete_cache(self):
  37. os.remove(self.fname)
  38. self.cache = {}
  39. self.fresh = True