Utilities
postprocess_copy_mutables(value: VT) -> VT
¶
Shallow-copy value before returning it (only dict, list, and set)
postprocess_copy(value: VT) -> VT
¶
postprocess_deepcopy_mutables(value: VT) -> VT
¶
Deep-copy value before returning it (only dict, list, and set)
postprocess_deepcopy(value: VT) -> VT
¶
make_key(*args, **kwds) -> typing.Hashable
¶
Default cache key.
Fast-path: a single int or str argument is returned as-is.
Otherwise a plain tuple (plus a kwargs sentinel when needed) is returned.
Source code in cachebox/utils.py
make_hash_key(*args, **kwds) -> int
¶
Key as the hash of all positional and keyword arguments.
Avoids storing the raw argument tuple, at the cost of potential hash collisions mapping distinct inputs to the same cache slot.
Source code in cachebox/utils.py
make_typed_key(*args, **kwds) -> tuple
¶
Key that includes the runtime type of every argument.
Ensures f(1) and f(1.0) are cached separately even though
1 == 1.0.
Source code in cachebox/utils.py
Frozen(cls: BaseCacheImpl[KT, VT], ignore: bool = False)
¶
A wrapper class that prevents modifications to an underlying cache implementation.
This class provides a read-only view of a cache, optionally allowing silent suppression of modification attempts instead of raising exceptions.
Example::
from cachebox import Frozen, FIFOCache
cache = FIFOCache(10, {1:1, 2:2, 3:3})
frozen = Frozen(cache, ignore=True)
print(frozen[1]) # 1
print(len(frozen)) # 3
# Frozen ignores this action and do nothing
frozen.insert("key", "value")
print(len(frozen)) # 3
# Let's try with ignore=False
frozen = Frozen(cache, ignore=False)
frozen.insert("key", "value")
# TypeError: This cache is frozen.
Initialize a frozen cache wrapper.
Parameters:
-
(cls¶BaseCacheImpl[KT, VT]) –The underlying cache implementation to be frozen.
-
(ignore¶bool, default:False) –If
True, silently ignores modification attempts; ifFalse, raisesTypeErrorwhen modification is attempted. Default isFalse.
Source code in cachebox/utils.py
cache: BaseCacheImpl[KT, VT]
property
¶
Returns the wrapped cache implementation.
getsizeof: typing.Callable[[KT, VT], int] | None
property
¶
Callable or None: The configured getsizeof function.
maxsize: int
property
¶
The configured maxsize.
__len__() -> int
¶
Returns the number of entries currently in the cache.
Returns:
-
int–The number of entries in the cache.
__new__(*args, **kwds) -> typing.Self
¶
Allocates memory and returns an uninitialized instance.
Warning
Using the returned instance before calling __init__ is unsafe
and causes panic errors.
capacity() -> int
¶
Returns the number of elements the map can hold without reallocating.
Returns:
-
int–The current allocated capacity.
clear(*, reuse: bool = False) -> None
¶
Removes all items from the cache.
Parameters:
-
(reuse¶bool, default:False) –If
True, retains the allocated memory for future reuse rather than freeing it. Defaults toFalse.
contains(key: KT) -> bool
¶
Returns True if the cache contains an entry for key.
Equivalent to key in self. Prefer this method over key in self
to keep code compatible across different cache policies.
Parameters:
-
(key¶KT) –The key to look up.
Returns:
-
bool–Trueif the key exists in the cache,Falseotherwise.
Source code in cachebox/utils.py
current_size() -> int
¶
Returns the current total cumulative size of all stored entries.
Returns:
-
int–The sum of sizes of all entries currently in the cache.
drain(n: int) -> int
¶
Calls popitem() n times and returns the count of removed items.
Parameters:
-
(n¶int) –The number of items to remove.
Returns:
-
int–The number of items successfully removed.
Source code in cachebox/utils.py
is_empty() -> bool
¶
Returns True if the cache is empty.
Returns:
-
bool–Trueif the cache contains no entries.
is_full() -> bool
¶
Returns True when the cumulative size has reached the maxsize limit.
Returns:
-
bool–Trueif the cache is at capacity.
pop(key: KT, default: DT = None) -> typing.Union[VT, DT]
¶
Removes the specified key and returns the corresponding value.
Parameters:
-
(key¶KT) –The key to remove.
-
(default¶DT, default:None) –Value to return if the key is not found.
Returns:
-
Union[VT, DT]–The value associated with
key, ordefaultif not found.
Raises:
-
KeyError–If the key is not found and no
defaultis provided.
Source code in cachebox/utils.py
remaining_size() -> int
¶
Returns the remaining available size.
Returns:
-
int–The result of
maxsize - current_size.
cached(cache: BaseCacheImpl | dict | typing.Callable[..., BaseCacheImpl] | None = None, key_maker: typing.Callable[..., typing.Hashable] = make_key, clear_reuse: bool = False, callback: _Callback | None = None, copy_level: int = 1, postprocess: _PostProcess | None = postprocess_copy_mutables, lock: typing.Type[AbstractContextManager] | typing.Type[AbstractAsyncContextManager] | bool | None = True) -> typing.Callable[[FT], FT]
¶
Decorator to memoize function/method results.
Parameters:
-
(cache¶BaseCacheImpl | dict | Callable[..., BaseCacheImpl] | None, default:None) –Cache instance,
dict, or callable(self) -> cachefor per-instance caches.Nonedefaults to an unbounded :class:LRUCache. -
(key_maker¶Callable[..., Hashable], default:make_key) –Converts
(args, kwds)to a hashable key. Built-ins: :func:make_key(default), :func:make_hash_key, :func:make_typed_key. -
(clear_reuse¶bool, default:False) –Pass
reuse=Truetocache.clear()when :func:cache_clearis called. -
(callback¶_Callback | None, default:None) –Called as
callback(event, key, value)on every hit/miss. May be a coroutine in async contexts. -
(copy_level¶int, default:1) –It has been deprecated and no longer has any effect. Use the postprocess parameter instead.
-
(postprocess¶_PostProcess | None, default:postprocess_copy_mutables) –Optional
(value) -> valuetransform applied before returning a result to the caller. Ready-to-use options:None- return the cached object as-is.- :func:
postprocess_copy- shallow-copy. - :func:
postprocess_copy_mutables- shallow-copy onlydict,listandset(default). - :func:
postprocess_deepcopy- deep-copy. - :func:
postprocess_deepcopy_mutables- deep-copy onlydict,listandset.
-
(lock¶Type[AbstractContextManager] | Type[AbstractAsyncContextManager] | bool | None, default:True) –If
NoneorFalse, cache stampede prevention get disabled, but process is still thread-safe. IfTrue, will usethreading.Lockorasyncio.Lockdepends on wrapped function. Also you can pass anything that implementedcontextlib.AbstractContextManager(orcontextlib.AbstractAsyncContextManagerfor async functions). (default isTrue). See cache stampede prevention for more.
Tip
Pass cachebox__ignore=True at call-time to bypass the cache.
If cache isn't a lambda/function, these attributes will be attached to
your function: cache (property), cache_info (callable), clear_cache (callable),
and callback (property).
Examples::
@cachebox.cached(cachebox.LRUCache(128))
def add(a, b):
return a + b
# Per-instance method cache
class Foo:
def __init__(self):
self._cache = cachebox.LRUCache(0)
@cachebox.cached(lambda self: self._cache)
def compute(self, n):
return n * 2
Source code in cachebox/utils.py
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 | |
is_cached(func: object) -> bool
¶
Return True if func was decorated with :func:cached.
Parameters:
-
(func¶object) –an object or function to check.
Source code in cachebox/utils.py
get_cached_cache(cached_func: object) -> BaseCacheImpl
¶
A way to get cached_func.cache, without type-hint warnings.
Parameters:
-
(cached_func¶object) –a function decorated with :func:
cached.
Warning
If func wasn't decorated with :func:cached, or you passed a lambda/function as cache
to :func:cached decorator, raises AttributeError.
Source code in cachebox/utils.py
get_cached_cache_info(cached_func: object) -> CacheInfo
¶
A way to get cached_func.cache_info(), without type-hint warnings.
Parameters:
-
(cached_func¶object) –a function decorated with :func:
cached.
Warning
If func wasn't decorated with :func:cached, or you passed a lambda/function as cache
to :func:cached decorator, raises AttributeError.
Source code in cachebox/utils.py
get_cached_callback(cached_func: object) -> _Callback | None
¶
A way to get cached_func.callback, without type-hint warnings.
Parameters:
-
(cached_func¶object) –a function decorated with :func:
cached.
Warning
If func wasn't decorated with :func:cached, or you passed a lambda/function as cache
to :func:cached decorator, raises AttributeError.
Source code in cachebox/utils.py
clear_cached_cache(cached_func: object) -> None
¶
A way to call cached_func.cache_clear(), without type-hint warnings.
Parameters:
-
(cached_func¶object) –a function decorated with :func:
cached.
Warning
If func wasn't decorated with :func:cached, or you passed a lambda/function as cache
to :func:cached decorator, raises AttributeError.