RefMap

Contents

RefMap#

class brainstate.graph.RefMap(mapping=())#

A mutable mapping that keys entries by object identity (id).

Two keys that compare equal but are distinct objects occupy distinct slots. This is the workhorse of graph flattening: it tracks which nodes and states have already been visited and the global integer index assigned to each, so that shared references deduplicate and cycles terminate.

Parameters:

mapping (Mapping[TypeVar(A), TypeVar(B)] | Iterable[tuple[TypeVar(A), TypeVar(B)]]) – Initial (key, value) pairs to populate the map with.

Notes

Lookups, insertions, and deletions are all keyed on id(key). The original key object is retained internally so that iteration yields the real keys (not their ids), and so keys are kept alive for the lifetime of the entry.

Examples

>>> from brainstate.graph import RefMap
>>> a, b = [1, 2, 3], [1, 2, 3]     # equal but distinct objects
>>> m = RefMap()
>>> m[a] = 0
>>> m[b] = 1
>>> len(m)                          # not collapsed by ==
2
>>> m[a]
0