diff --git a/zammadoo/cache.py b/zammadoo/cache.py index 91db820..17b318f 100644 --- a/zammadoo/cache.py +++ b/zammadoo/cache.py @@ -10,17 +10,17 @@ class LruCache(Generic[_T]): - def __init__(self, max_size=-1) -> None: + def __init__(self, max_size: int = -1) -> None: self._cache: "OrderedDict[Hashable, Tuple[datetime, _T]]" = OrderedDict() self._max_size = max_size @property - def max_size(self): + def max_size(self) -> int: return self._max_size @max_size.setter def max_size(self, value: int): - self._max_size = value + self._max_size = max(value, -1) if value == 0: self._cache.clear() elif value > 0: @@ -41,15 +41,15 @@ def setdefault(self, item, default: _T) -> _T: return default cache = self._cache + if item in cache: - if max_size > 1: - cache.move_to_end(item) + cache.move_to_end(item) return cache[item][1] - cache[item] = datetime.now(timezone.utc), default - if 0 < max_size < len(cache): + if 0 < max_size <= len(cache): cache.popitem(last=False) + cache[item] = datetime.now(timezone.utc), default return default def clear(self) -> None: @@ -72,8 +72,7 @@ def __contains__(self, item: Hashable): def __getitem__(self, item: Hashable) -> _T: cache = self._cache - if self._max_size > 1: - cache.move_to_end(item) + cache.move_to_end(item) return cache[item][1] def __setitem__(self, item: Hashable, value: _T) -> None: @@ -94,5 +93,5 @@ def __delitem__(self, item: Hashable) -> None: del self._cache[item] def timestamp(self, item: Hashable) -> Optional[datetime]: - data = self._cache.get(item) - return data and data[0] + data = self._cache.get(item, (None, None)) + return data[0]