BoundedCache#

class brainstate.util.BoundedCache(maxsize=128)[source]#

A thread-safe LRU cache with bounded size.

This cache stores a limited number of items and evicts the least recently used item when the cache reaches its maximum size. All operations are thread-safe.

Parameters:

maxsize (int) – Maximum number of items to store in the cache.

clear()[source]#

Clear all items from the cache and reset statistics.

This method removes all cached items and resets hit/miss counters to zero.

Return type:

None

get(key, default=None, raise_on_miss=False, error_context='item')[source]#

Get an item from the cache.

Parameters:
  • key (Any) – The cache key.

  • default (Any) – The default value to return if the key is not found.

  • raise_on_miss (bool) – If True, raise a detailed ValueError when the key is not found.

  • error_context (str) – Context description for the error message (e.g., “Function”, “JAX expression”).

Returns:

The cached value or the default value.

Return type:

Any

Raises:

ValueError – If raise_on_miss is True and the key is not found.

get_stats()[source]#

Get cache statistics.

Returns:

A dictionary with cache statistics including:

  • ’size’: Current number of items in cache

  • ’maxsize’: Maximum cache size

  • ’hits’: Number of cache hits

  • ’misses’: Number of cache misses

  • ’hit_rate’: Hit rate percentage (0-100)

Return type:

Dict[str, Any]

keys()[source]#

Return all keys in the cache.

Returns:

A list of all keys currently in the cache.

Return type:

list

property maxsize: int#

Get the maximum size of the cache.

pop(key, default=None)[source]#

Remove and return an item from the cache.

Parameters:
  • key (Any) – The cache key to remove.

  • default (Any) – The default value to return if the key is not found.

Returns:

The cached value or the default value if the key is not found.

Return type:

Any

replace(key, value)[source]#

Replace an existing item in the cache.

Parameters:
  • key (Any) – The cache key to replace.

  • value (Any) – The new value to cache.

Raises:

KeyError – If the key does not exist in the cache.

Return type:

None

set(key, value)[source]#

Set an item in the cache.

Parameters:
  • key (Any) – The cache key.

  • value (Any) – The value to cache.

Raises:

ValueError – If the key already exists in the cache.

Return type:

None