API Reference¶
TTLCachedFunction¶
TTLCachedFunction
¶
Bases: Protocol
Same signature as the wrapped function, plus lru_cache's helpers.
ttl_lru_cache¶
ttl_lru_cache
¶
A decorator that works like lru_cache but with a time to live (ttl).
Under the hood it still uses lru_cache, but the cached call receives an
extra positional-only time_bucket argument:
time_bucket = int((time.monotonic() + offset) // ttl)
An entry stays "alive" while the bucket value is unchanged and expires when
the bucket rolls over. offset is drawn once per decorated function from
random.uniform(0, jitter), so different functions (or processes) expire
at different moments instead of all at once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ttl
|
float
|
Time to live in seconds. Defaults to 60. |
60
|
jitter
|
float
|
Max random offset in seconds applied to the bucket boundaries. Defaults to 0. |
0
|
maxsize
|
int | None
|
Max size of the cache, or |
128
|
typed
|
bool
|
Whether argument types are part of the cache key. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[P, R]], TTLCachedFunction[P, R]]
|
A decorator that wraps a function in a TTL-aware LRU cache. The wrapped |
Callable[[Callable[P, R]], TTLCachedFunction[P, R]]
|
function keeps its signature and exposes |
Callable[[Callable[P, R]], TTLCachedFunction[P, R]]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example:
>>> @ttl_lru_cache(ttl=30, jitter=5)
... def fetch(key: str) -> str:
... return key.upper()