Lets you submit and vote on images
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

38 рядки
1.1 KiB

  1. import time
  2. class MWT(object):
  3. """Memoize With Timeout"""
  4. _caches = {}
  5. _timeouts = {}
  6. def __init__(self,timeout=2):
  7. self.timeout = timeout
  8. def collect(self):
  9. """Clear cache of results which have timed out"""
  10. for func in self._caches:
  11. cache = {}
  12. for key in self._caches[func]:
  13. if (time.time() - self._caches[func][key][1]) < self._timeouts[func]:
  14. cache[key] = self._caches[func][key]
  15. self._caches[func] = cache
  16. def __call__(self, f):
  17. self.cache = self._caches[f] = {}
  18. self._timeouts[f] = self.timeout
  19. def func(*args, **kwargs):
  20. kw = sorted(kwargs.items())
  21. key = (args, tuple(kw))
  22. try:
  23. v = self.cache[key]
  24. print("cache")
  25. if (time.time() - v[1]) > self.timeout:
  26. raise KeyError
  27. except KeyError:
  28. print("new")
  29. v = self.cache[key] = f(*args,**kwargs),time.time()
  30. return v[0]
  31. func.func_name = f.__name__
  32. return func