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.
CacheInfo = namedtuple('CacheInfo', ('hits', 'misses', 'maxsize', 'current_size', 'length', 'memory'))
module-attribute
¶
EVENT_MISS = 1
module-attribute
¶
EVENT_HIT = 2
module-attribute
¶
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) -> 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.
Note
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
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 | |
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.