Skip to content

Commit

Permalink
LruCache.evict() also prunes cache by maximum age
Browse files Browse the repository at this point in the history
Signed-off-by: flashdagger <flashdagger@googlemail.com>
  • Loading branch information
flashdagger committed Jul 27, 2024
1 parent e08d2a8 commit 9598318
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
17 changes: 14 additions & 3 deletions tests/test_cache.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import time
from itertools import zip_longest
from operator import eq

Expand Down Expand Up @@ -158,9 +159,6 @@ def test_clear():


def test_age_s():
import time
from datetime import datetime, timezone

cache = LruCache()
assert cache.age_s("foo") is None

Expand All @@ -170,3 +168,16 @@ def test_age_s():
assert cache.age_s("foo") > 0.015
cache["foo"] = "baz"
assert cache.age_s("foo") < 0.015


def test_evict_by_age():
cache = LruCache()
cache["first"] = None
time.sleep(0.015)
cache["second"] = None

cache.evict()
assert cache.keys() == {"first", "second"}

cache.evict(max_age_s=0.015)
assert cache.keys() == {"second"}
12 changes: 9 additions & 3 deletions zammadoo/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from collections import OrderedDict
from collections.abc import Hashable
from time import monotonic
from typing import Generic, Optional, Tuple, TypeVar
from typing import Generic, Optional, Tuple, TypeVar, Union

_T = TypeVar("_T")

Expand All @@ -22,12 +22,18 @@ def max_size(self, value: int):
self._max_size = max(value, -1)
self.evict()

def evict(self) -> None:
def evict(self, max_age_s: Union[None, int, float] = None) -> None:
cache = self._cache
if max_age_s is not None:
min_timestamp = monotonic() - max_age_s
outdated = [key for key, value in cache.items() if value[0] < min_timestamp]
for key in outdated:
del cache[key]

max_size = self._max_size
if max_size < 0:
return

cache = self._cache
if max_size == 0:
cache.clear()
return
Expand Down

0 comments on commit 9598318

Please sign in to comment.