Skip to content

Commit 2cb42c7

Browse files
committed
prune timed_cache
1 parent 0ba5016 commit 2cb42c7

1 file changed

Lines changed: 9 additions & 10 deletions

File tree

franklinwh/client.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -28,20 +28,19 @@ def time_cached(ttl: timedelta = timedelta(seconds=2)):
2828

2929
def wrapper(func):
3030
cache = {}
31+
lock = asyncio.Lock()
3132

3233
@wraps(func)
3334
async def wrapped(*args, **kwargs):
34-
now = datetime.now()
35-
key = (func.__name__, args, frozenset(kwargs.items()))
36-
if key not in cache:
37-
cache[key] = (now - ttl, None, asyncio.Lock())
38-
lock = cache[key][2]
3935
async with lock:
40-
if now < cache[key][0]:
41-
return cache[key][1]
42-
result = await func(*args, **kwargs)
43-
cache[key] = (now + ttl, result, lock)
44-
return result
36+
now = datetime.now()
37+
for key, value in cache.copy().items():
38+
if now > value[0]:
39+
del cache[key]
40+
key = (func.__name__, args, frozenset(kwargs.items()))
41+
if key not in cache:
42+
cache[key] = (now + ttl, await func(*args, **kwargs))
43+
return cache[key][1]
4544

4645
setattr(wrapped, "clear", cache.clear)
4746
return wrapped

0 commit comments

Comments
 (0)