Coverage for src/manimgx/caches.py: 100%
34 statements
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-26 05:52 +0000
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-26 05:52 +0000
1"""What ManimGX remembers: values it has worked out once, kept to be read again.
3Every such memory is a `Memo`: bounded (past its limit it forgets everything at once) and
4invisible (forgetting changes no result, only the time one takes). `clear` forgets them all,
5as the tests do to show that nothing depends on what is remembered.
7What an object holds is remembered the same way: a value assigned equal to the one it holds
8(`unchanged`) keeps the one held, and so all that was derived from it — an upload, normals, a
9frame's record."""
11from collections.abc import Callable, Hashable
13import numpy as np
15_FORGETTERS: list[Callable[[], None]] = []
18def unchanged(value: np.ndarray, held: object) -> bool:
19 """Is `value` the array `held`, bit for bit (so that keeping the one held changes nothing)?
20 An array of up to 1,024 items is compared whole; a bigger one at 16 items spread over it
21 first, so that one that changed is told at once."""
22 if value is held:
23 return True
24 if not (
25 isinstance(held, np.ndarray)
26 and value.shape == held.shape
27 and value.dtype == held.dtype
28 ):
29 return False
30 if value.size <= 1024:
31 return value.tobytes() == held.tobytes()
32 bits = f"u{value.itemsize}" # the items' bits, compared as unsigned integers
33 items, kept = value.reshape(-1).view(bits), held.reshape(-1).view(bits)
34 step = len(items) // 16
35 return bool(
36 np.array_equal(items[::step], kept[::step]) and np.array_equal(items, kept)
37 )
40class Memo[K: Hashable, V](dict[K, V]):
41 """A value for each key, worked out once: `memo.recall(key, make)`.
43 Args:
44 limit: How many values it keeps; past it, it forgets them all.
45 """
47 __slots__ = ("limit",)
49 def __init__(self, limit: int) -> None:
50 super().__init__()
51 self.limit = limit
52 _FORGETTERS.append(self.clear)
54 def recall(self, key: K, make: Callable[[], V]) -> V:
55 """The value for `key`: remembered, or made now by `make` and remembered."""
56 value = self.get(key)
57 return self.keep(key, make()) if value is None else value
59 def keep(self, key: K, value: V) -> V:
60 """Remember `value` for `key` (forgetting everything first, past the limit)."""
61 if len(self) >= self.limit:
62 self.clear()
63 self[key] = value
64 return value
67def forgets[F: Callable[..., object]](cached: F) -> F:
68 """Have `clear` forget a function's own cache too (a `functools.cache`)."""
69 _FORGETTERS.append(getattr(cached, "cache_clear")) # noqa: B009
70 return cached
73def clear() -> None:
74 """Forget everything remembered."""
75 for forget in _FORGETTERS:
76 forget()