|
12 | 12 | # See the License for the specific language governing permissions and |
13 | 13 | # limitations under the License. |
14 | 14 |
|
| 15 | +"""LRU Implementation. |
| 16 | +
|
| 17 | +This is currently re-exported in task_cache.py |
| 18 | +""" |
| 19 | + |
15 | 20 | from __future__ import annotations |
16 | 21 |
|
17 | 22 | __all__ = ("LRU",) |
18 | 23 |
|
19 | 24 |
|
20 | 25 | class LRU[K, V]: |
21 | | - def __init__(self, maxsize: int, /): |
22 | | - self.cache: dict[K, V] = {} |
23 | | - self.maxsize = maxsize |
| 26 | + """An LRU implementation. |
| 27 | +
|
| 28 | + Parameters |
| 29 | + ---------- |
| 30 | + maxsize: int |
| 31 | + The maximum number of items to retain |
| 32 | + """ |
| 33 | + |
| 34 | + def __init__(self, maxsize: int, /) -> None: |
| 35 | + self._cache: dict[K, V] = {} |
| 36 | + self._maxsize = maxsize |
24 | 37 |
|
25 | 38 | def get[T](self, key: K, default: T, /) -> V | T: |
| 39 | + """Get a value by key or default value. |
| 40 | +
|
| 41 | + You should only use this when you have a default. |
| 42 | + Otherwise, use index into the LRU by key. |
| 43 | +
|
| 44 | + Args: |
| 45 | + key: The key to lookup a value for |
| 46 | + default: A default value |
| 47 | +
|
| 48 | + Returns |
| 49 | + ------- |
| 50 | + Either the value associated to a key-value pair in the LRU |
| 51 | + or the specified default |
| 52 | +
|
| 53 | + """ |
26 | 54 | try: |
27 | 55 | return self[key] |
28 | 56 | except KeyError: |
29 | 57 | return default |
30 | 58 |
|
31 | 59 | def __getitem__(self, key: K, /) -> V: |
32 | | - val = self.cache[key] = self.cache.pop(key) |
| 60 | + val = self._cache[key] = self._cache.pop(key) |
33 | 61 | return val |
34 | 62 |
|
35 | | - def __setitem__(self, key: K, value: V, /): |
36 | | - self.cache[key] = value |
37 | | - if len(self.cache) > self.maxsize: |
38 | | - self.cache.pop(next(iter(self.cache))) |
| 63 | + def __setitem__(self, key: K, value: V, /) -> None: |
| 64 | + self._cache[key] = value |
| 65 | + if len(self._cache) > self._maxsize: |
| 66 | + self._cache.pop(next(iter(self._cache))) |
39 | 67 |
|
40 | 68 | def remove(self, key: K, /) -> None: |
41 | | - self.cache.pop(key, None) |
| 69 | + self._cache.pop(key, None) |
0 commit comments