cache.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. from __future__ import annotations
  2. from collections import deque
  3. from functools import wraps
  4. from typing import Any, Callable, Dict, Generic, Hashable, Tuple, TypeVar, cast
  5. __all__ = [
  6. "SimpleCache",
  7. "FastDictCache",
  8. "memoized",
  9. ]
  10. _T = TypeVar("_T", bound=Hashable)
  11. _U = TypeVar("_U")
  12. class SimpleCache(Generic[_T, _U]):
  13. """
  14. Very simple cache that discards the oldest item when the cache size is
  15. exceeded.
  16. :param maxsize: Maximum size of the cache. (Don't make it too big.)
  17. """
  18. def __init__(self, maxsize: int = 8) -> None:
  19. assert maxsize > 0
  20. self._data: dict[_T, _U] = {}
  21. self._keys: deque[_T] = deque()
  22. self.maxsize: int = maxsize
  23. def get(self, key: _T, getter_func: Callable[[], _U]) -> _U:
  24. """
  25. Get object from the cache.
  26. If not found, call `getter_func` to resolve it, and put that on the top
  27. of the cache instead.
  28. """
  29. # Look in cache first.
  30. try:
  31. return self._data[key]
  32. except KeyError:
  33. # Not found? Get it.
  34. value = getter_func()
  35. self._data[key] = value
  36. self._keys.append(key)
  37. # Remove the oldest key when the size is exceeded.
  38. if len(self._data) > self.maxsize:
  39. key_to_remove = self._keys.popleft()
  40. if key_to_remove in self._data:
  41. del self._data[key_to_remove]
  42. return value
  43. def clear(self) -> None:
  44. "Clear cache."
  45. self._data = {}
  46. self._keys = deque()
  47. _K = TypeVar("_K", bound=Tuple[Hashable, ...])
  48. _V = TypeVar("_V")
  49. class FastDictCache(Dict[_K, _V]):
  50. """
  51. Fast, lightweight cache which keeps at most `size` items.
  52. It will discard the oldest items in the cache first.
  53. The cache is a dictionary, which doesn't keep track of access counts.
  54. It is perfect to cache little immutable objects which are not expensive to
  55. create, but where a dictionary lookup is still much faster than an object
  56. instantiation.
  57. :param get_value: Callable that's called in case of a missing key.
  58. """
  59. # NOTE: This cache is used to cache `prompt_toolkit.layout.screen.Char` and
  60. # `prompt_toolkit.Document`. Make sure to keep this really lightweight.
  61. # Accessing the cache should stay faster than instantiating new
  62. # objects.
  63. # (Dictionary lookups are really fast.)
  64. # SimpleCache is still required for cases where the cache key is not
  65. # the same as the arguments given to the function that creates the
  66. # value.)
  67. def __init__(self, get_value: Callable[..., _V], size: int = 1000000) -> None:
  68. assert size > 0
  69. self._keys: deque[_K] = deque()
  70. self.get_value = get_value
  71. self.size = size
  72. def __missing__(self, key: _K) -> _V:
  73. # Remove the oldest key when the size is exceeded.
  74. if len(self) > self.size:
  75. key_to_remove = self._keys.popleft()
  76. if key_to_remove in self:
  77. del self[key_to_remove]
  78. result = self.get_value(*key)
  79. self[key] = result
  80. self._keys.append(key)
  81. return result
  82. _F = TypeVar("_F", bound=Callable[..., object])
  83. def memoized(maxsize: int = 1024) -> Callable[[_F], _F]:
  84. """
  85. Memoization decorator for immutable classes and pure functions.
  86. """
  87. def decorator(obj: _F) -> _F:
  88. cache: SimpleCache[Hashable, Any] = SimpleCache(maxsize=maxsize)
  89. @wraps(obj)
  90. def new_callable(*a: Any, **kw: Any) -> Any:
  91. def create_new() -> Any:
  92. return obj(*a, **kw)
  93. key = (a, tuple(sorted(kw.items())))
  94. return cache.get(key, create_new)
  95. return cast(_F, new_callable)
  96. return decorator