cache#

Provides an in-memory dictionary-style cache for intermediate storage in KnotPy.

This cache limits the number of entries and key lengths, and replaces the longest key when full. Designed for fast, dependency-free use in performance-sensitive contexts.

Classes

Cache(max_cache_size, max_key_length)

In-memory bounded-size cache for key-value pairs with limited key lengths.

class Cache(max_cache_size, max_key_length)#

Bases: dict[Hashable, Any]

In-memory bounded-size cache for key-value pairs with limited key lengths.

This cache:
  • Limits the total number of items (max_cache_size).

  • Skips keys whose length (len(key)) exceeds max_key_length.

  • When full, evicts the entry with the longest key if the incoming key is shorter.

Notes

  • Keys must be hashable. If a key has no length (i.e., len(key) raises TypeError), it is ignored (not cached).

  • Updating an existing key always succeeds (no eviction), even when the cache is full.

Example

>>> cache = Cache(max_cache_size=3, max_key_length=5)
>>> cache['abc'] = 1
>>> cache['def'] = 2
>>> cache['ghi'] = 3
>>> cache['abcdef'] = 4  # ignored: key too long
>>> list(cache.items())
[('abc', 1), ('def', 2), ('ghi', 3)]
Parameters:
  • max_cache_size (int)

  • max_key_length (int)

max_cache_size#

Maximum number of entries the cache can hold (<=0 disables caching).

Type:

int

max_key_length#

Maximum allowed length of any key.

Type:

int