Skip to content

Commit

Permalink
refactor cache.py
Browse files Browse the repository at this point in the history
* type annotation
* set lower bound of max_size to -1
* refactor setdefault(), __getitem__(), timestamp()

Signed-off-by: flashdagger <flashdagger@googlemail.com>
  • Loading branch information
flashdagger committed Jul 26, 2024
1 parent fccb5ee commit 3441970
Showing 1 changed file with 10 additions and 11 deletions.
21 changes: 10 additions & 11 deletions zammadoo/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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]

0 comments on commit 3441970

Please sign in to comment.