|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from collections import OrderedDict |
| 4 | +from collections.abc import MutableMapping |
| 5 | +from typing import TYPE_CHECKING, Any, TypeVar, overload |
| 6 | + |
| 7 | +from polars._utils.various import no_default |
| 8 | + |
| 9 | +if TYPE_CHECKING: |
| 10 | + import sys |
| 11 | + from collections.abc import ItemsView, Iterable, Iterator, KeysView, ValuesView |
| 12 | + |
| 13 | + from polars._utils.various import NoDefault |
| 14 | + |
| 15 | + if sys.version_info >= (3, 11): |
| 16 | + from typing import Self |
| 17 | + else: |
| 18 | + from typing_extensions import Self |
| 19 | + |
| 20 | +D = TypeVar("D") |
| 21 | +K = TypeVar("K") |
| 22 | +V = TypeVar("V") |
| 23 | + |
| 24 | + |
| 25 | +class LRUCache(MutableMapping[K, V]): |
| 26 | + def __init__(self, maxsize: int) -> None: |
| 27 | + """ |
| 28 | + Initialize an LRU (Least Recently Used) cache with a specified maximum size. |
| 29 | +
|
| 30 | + Parameters |
| 31 | + ---------- |
| 32 | + maxsize : int |
| 33 | + The maximum number of items the cache can hold. |
| 34 | +
|
| 35 | + Examples |
| 36 | + -------- |
| 37 | + >>> from polars._utils.cache import LRUCache |
| 38 | + >>> cache = LRUCache[str, int](maxsize=3) |
| 39 | + >>> cache["a"] = 1 |
| 40 | + >>> cache["b"] = 2 |
| 41 | + >>> cache["c"] = 3 |
| 42 | + >>> cache["d"] = 4 # evicts the least recently used item ("a"), as maxsize=3 |
| 43 | + >>> print(cache["b"]) # accessing "b" marks it as recently used |
| 44 | + 2 |
| 45 | + >>> print(list(cache.keys())) # show the current keys in LRU order |
| 46 | + ['c', 'd', 'b'] |
| 47 | + >>> cache.get("xyz", "not found") |
| 48 | + 'not found' |
| 49 | + """ |
| 50 | + self._items: OrderedDict[K, V] = OrderedDict() |
| 51 | + self.maxsize = maxsize |
| 52 | + |
| 53 | + def __bool__(self) -> bool: |
| 54 | + """Returns True if the cache is not empty, False otherwise.""" |
| 55 | + return bool(self._items) |
| 56 | + |
| 57 | + def __contains__(self, key: Any) -> bool: |
| 58 | + """Check if the key is in the cache.""" |
| 59 | + return key in self._items |
| 60 | + |
| 61 | + def __delitem__(self, key: K) -> None: |
| 62 | + """Remove the item with the specified key from the cache.""" |
| 63 | + if key not in self._items: |
| 64 | + msg = f"{key!r} not found in cache" |
| 65 | + raise KeyError(msg) |
| 66 | + del self._items[key] |
| 67 | + |
| 68 | + def __getitem__(self, key: K) -> V: |
| 69 | + """Raises KeyError if the key is not found.""" |
| 70 | + if key not in self._items: |
| 71 | + msg = f"{key!r} not found in cache" |
| 72 | + raise KeyError(msg) |
| 73 | + |
| 74 | + # moving accessed items to the end marks them as recently used |
| 75 | + self._items.move_to_end(key) |
| 76 | + return self._items[key] |
| 77 | + |
| 78 | + def __iter__(self) -> Iterator[K]: |
| 79 | + """Iterate over the keys in the cache.""" |
| 80 | + yield from self._items |
| 81 | + |
| 82 | + def __len__(self) -> int: |
| 83 | + """Number of items in the cache.""" |
| 84 | + return len(self._items) |
| 85 | + |
| 86 | + def __setitem__(self, key: K, value: V) -> None: |
| 87 | + """Insert a value into the cache.""" |
| 88 | + if self._max_size == 0: |
| 89 | + return |
| 90 | + while len(self) >= self._max_size: |
| 91 | + self.popitem() |
| 92 | + if key in self: |
| 93 | + # moving accessed items to the end marks them as recently used |
| 94 | + self._items.move_to_end(key) |
| 95 | + self._items[key] = value |
| 96 | + |
| 97 | + def __repr__(self) -> str: |
| 98 | + """Return a string representation of the cache.""" |
| 99 | + all_items = list(self._items.items()) |
| 100 | + if len(self) > 4: |
| 101 | + items = ( |
| 102 | + ", ".join(f"{k!r}: {v!r}" for k, v in all_items[:2]) |
| 103 | + + " ..., " |
| 104 | + + ", ".join(f"{k!r}: {v!r}" for k, v in all_items[-2:]) |
| 105 | + ) |
| 106 | + else: |
| 107 | + items = ", ".join(f"{k!r}: {v!r}" for k, v in all_items) |
| 108 | + return f"{self.__class__.__name__}({{{items}}}, maxsize={self._max_size}, currsize={len(self)})" |
| 109 | + |
| 110 | + def clear(self) -> None: |
| 111 | + """Clear the cache, removing all items.""" |
| 112 | + self._items.clear() |
| 113 | + |
| 114 | + @overload |
| 115 | + def get(self, key: K, default: None = None) -> V | None: ... |
| 116 | + |
| 117 | + @overload |
| 118 | + def get(self, key: K, default: D = ...) -> V | D: ... |
| 119 | + |
| 120 | + def get(self, key: K, default: D | V | None = None) -> V | D | None: |
| 121 | + """Return value associated with `key` if present, otherwise return `default`.""" |
| 122 | + if key in self: |
| 123 | + # moving accessed items to the end marks them as recently used |
| 124 | + self._items.move_to_end(key) |
| 125 | + return self._items[key] |
| 126 | + return default |
| 127 | + |
| 128 | + @classmethod |
| 129 | + def fromkeys(cls, maxsize: int, *, keys: Iterable[K], value: V) -> Self: |
| 130 | + """Initialize cache with keys from an iterable, all set to the same value.""" |
| 131 | + cache = cls(maxsize) |
| 132 | + for key in keys: |
| 133 | + cache[key] = value |
| 134 | + return cache |
| 135 | + |
| 136 | + def items(self) -> ItemsView[K, V]: |
| 137 | + """Return an iterable view of the cache's items (keys and values).""" |
| 138 | + return self._items.items() |
| 139 | + |
| 140 | + def keys(self) -> KeysView[K]: |
| 141 | + """Return an iterable view of the cache's keys.""" |
| 142 | + return self._items.keys() |
| 143 | + |
| 144 | + @property |
| 145 | + def maxsize(self) -> int: |
| 146 | + return self._max_size |
| 147 | + |
| 148 | + @maxsize.setter |
| 149 | + def maxsize(self, n: int) -> None: |
| 150 | + """Set new maximum cache size; cache is trimmed if value is smaller.""" |
| 151 | + if n < 0: |
| 152 | + msg = f"`maxsize` cannot be negative; found {n}" |
| 153 | + raise ValueError(msg) |
| 154 | + while len(self) > n: |
| 155 | + self.popitem() |
| 156 | + self._max_size = n |
| 157 | + |
| 158 | + def pop(self, key: K, default: D | NoDefault = no_default) -> V | D: |
| 159 | + """ |
| 160 | + Remove specified key from the cache and return the associated value. |
| 161 | +
|
| 162 | + If the key is not found, `default` is returned (if given). |
| 163 | + Otherwise, a KeyError is raised. |
| 164 | + """ |
| 165 | + if (item := self._items.pop(key, default)) is no_default: |
| 166 | + msg = f"{key!r} not found in cache" |
| 167 | + raise KeyError(msg) |
| 168 | + return item |
| 169 | + |
| 170 | + def popitem(self) -> tuple[K, V]: |
| 171 | + """Remove the least recently used value; raises KeyError if cache is empty.""" |
| 172 | + return self._items.popitem(last=False) |
| 173 | + |
| 174 | + def values(self) -> ValuesView[V]: |
| 175 | + """Return an iterable view of the cache's values.""" |
| 176 | + return self._items.values() |
0 commit comments