-
Notifications
You must be signed in to change notification settings - Fork 93
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
23 changed files
with
1,465 additions
and
910 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import functools | ||
from collections import OrderedDict | ||
from collections.abc import Awaitable | ||
|
||
|
||
def async_lru_cache(maxsize: int = 128): | ||
""" | ||
Caches a function's return value each time it is called. | ||
If the maxsize is reached, the least recently used value is removed. | ||
""" | ||
|
||
def decorator(func): | ||
cache: OrderedDict[tuple, Awaitable] = OrderedDict() | ||
|
||
@functools.wraps(func) | ||
async def wrapper(*args, **kwargs) -> Awaitable: | ||
# Create a cache key from args and kwargs, using frozenset for kwargs to ensure hashability | ||
key = (args, frozenset(kwargs.items())) | ||
|
||
if key in cache: | ||
# Move the recently accessed key to the end (most recently used) | ||
cache.move_to_end(key) | ||
return cache[key] | ||
|
||
# Compute the value since it's not cached | ||
value = await func(*args, **kwargs) | ||
cache[key] = value | ||
cache.move_to_end(key) | ||
|
||
if len(cache) > maxsize: | ||
cache.popitem(last=False) | ||
|
||
return value | ||
|
||
return wrapper | ||
|
||
return decorator |
Oops, something went wrong.