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
2.0 KiB

  1. ###################################################################################
  2. #
  3. # Copyright (C) 2018 MuK IT GmbH
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. #
  18. ###################################################################################
  19. import time
  20. class memoize(object):
  21. _caches = {}
  22. _timeouts = {}
  23. def __init__(self, timeout=2):
  24. self.timeout = timeout
  25. def collect(self):
  26. for func in self._caches:
  27. cleaned_cache = {}
  28. current_time = time.time()
  29. for key in self._caches[func]:
  30. if (current_time - self._caches[func][key][1]) < self._timeouts[func]:
  31. cleaned_cache[key] = self._caches[func][key]
  32. self._caches[func] = cleaned_cache
  33. def __call__(self, func):
  34. self.cache = self._caches[func] = {}
  35. self._timeouts[func] = self.timeout
  36. def wrapper(*args, **kwargs):
  37. current_time = time.time()
  38. kw = sorted(kwargs.items())
  39. key = (args, tuple(kw))
  40. try:
  41. value = self.cache[key]
  42. if (current_time - value[1]) > self.timeout:
  43. raise KeyError
  44. except KeyError:
  45. value = self.cache[key] = (func(*args,**kwargs), current_time)
  46. return value[0]
  47. wrapper.func_name = func.__name__
  48. return wrapper