Skip to content

Commit

Permalink
chore: improved typing of LRUCache
Browse files Browse the repository at this point in the history
  • Loading branch information
ntamas committed Apr 22, 2024
1 parent 8652c9e commit c67a1b6
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions src/modules/sbstudio/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from collections.abc import MutableMapping
from functools import wraps
from pathlib import Path
from typing import Any, Callable, List, Sequence, TypeVar
from typing import Any, Callable, Generic, List, Sequence, TypeVar

from sbstudio.model.types import Coordinate3D

Expand All @@ -17,6 +17,8 @@
)

T = TypeVar("T")
K = TypeVar("K")
V = TypeVar("V")


def constant(value: Any) -> Callable[..., Any]:
Expand Down Expand Up @@ -119,9 +121,11 @@ def load_module(path: str) -> Any:
return module


class LRUCache(MutableMapping):
class LRUCache(Generic[K, V], MutableMapping[K, V]):
"""Size-limited cache with least-recently-used eviction policy."""

_items: OrderedDict[K, V]

def __init__(self, capacity: int):
"""Constructor.
Expand All @@ -131,7 +135,7 @@ def __init__(self, capacity: int):
self._items = OrderedDict()
self._capacity = max(int(capacity), 1)

def __delitem__(self, key):
def __delitem__(self, key: K) -> None:
del self._items[key]

def __iter__(self):
Expand All @@ -140,21 +144,21 @@ def __iter__(self):
def __len__(self) -> int:
return len(self._items)

def __setitem__(self, key, value):
def __setitem__(self, key: K, value: V):
self._items[key] = value
self._items.move_to_end(key)
if len(self._items) > self._capacity:
self._items.popitem(last=False)

def get(self, key):
def get(self, key: K) -> V:
"""Returns the value corresponding to the given key, marking the key as
recently accessed.
"""
value = self._items[key]
self._items.move_to_end(key)
return value

def peek(self, key):
def peek(self, key: K) -> V:
"""Returns the value corresponding to the given key, _without_ marking
the key as recently accessed.
"""
Expand Down

0 comments on commit c67a1b6

Please sign in to comment.