Skip to content

qten.utils.collections_ext

Module reference for qten.utils.collections_ext.

collections_ext

Collection helpers used across QTen.

This module provides small extensions around Python collection protocols. The main public type, FrozenDict, is an immutable, hashable mapping used where configuration dictionaries need stable identity in caches or exported records.

FrozenDict

FrozenDict(*args: Any, **kwargs: Any)

Bases: Mapping[_K, _V], Generic[_K, _V]

Immutable hashable dictionary-like mapping.

FrozenDict stores its items as an immutable frozenset-backed payload so instances can be hashed and used as dictionary keys or cache entries, provided all keys and values are hashable.

Parameters:

Name Type Description Default
*args Any

Positional arguments accepted by the built-in dict constructor.

()
**kwargs Any

Keyword arguments accepted by the built-in dict constructor.

{}

Raises:

Type Description
TypeError

If any key or value is not hashable.

Examples:

options = FrozenDict({"method": "exact", "maxiter": 100})
cache = {options: "result"}
Source code in src/qten/utils/collections_ext.py
59
60
61
62
63
64
65
66
67
68
69
70
71
def __init__(self, *args: Any, **kwargs: Any):
    data = dict(*args, **kwargs)
    try:
        fitems = frozenset(data.items())  # ensures all keys/vals are hashable
    except TypeError as e:
        raise TypeError(
            "All keys and values must be hashable. "
            "Use deep_freeze() for nested mutables."
        ) from e
    object.__setattr__(
        self, "_FrozenDict__items", tuple(fitems)
    )  # hidden, immutable
    object.__setattr__(self, "_FrozenDict__hash", hash(fitems))

__slots__ class-attribute instance-attribute

__slots__ = ('__items', '__hash')

__len__

__len__() -> int
Source code in src/qten/utils/collections_ext.py
81
82
def __len__(self) -> int:
    return len(self._items())

__iter__

__iter__() -> Iterator[_K]
Source code in src/qten/utils/collections_ext.py
84
85
86
def __iter__(self) -> Iterator[_K]:
    for k, _ in self._items():
        yield k

__getitem__

__getitem__(key: _K) -> _V
Source code in src/qten/utils/collections_ext.py
88
89
90
91
92
def __getitem__(self, key: _K) -> _V:
    for k, v in self._items():
        if k == key:
            return v
    raise KeyError(key)

__hash__

__hash__() -> int
Source code in src/qten/utils/collections_ext.py
95
96
def __hash__(self) -> int:
    return object.__getattribute__(self, "_FrozenDict__hash")

__str__

__str__() -> str
Source code in src/qten/utils/collections_ext.py
108
109
def __str__(self) -> str:
    return str(dict(self._items()))

__repr__

__repr__() -> str
Source code in src/qten/utils/collections_ext.py
111
112
def __repr__(self) -> str:
    return repr(dict(self._items()))

__getattribute__

__getattribute__(name: str)
Source code in src/qten/utils/collections_ext.py
114
115
116
117
def __getattribute__(self, name: str):
    if name in {"_FrozenDict__items"}:
        raise AttributeError("Private storage is hidden")
    return super().__getattribute__(name)

matchby

matchby(
    source: Iterable[Any],
    dest: Iterable[Any],
    base_func: Callable[[Any], Any],
) -> Dict[Any, Any]

Map elements from source to destination using a provided mapping function.

For each element in source, base_func is evaluated and matched against exactly one element in dest with the same baseline value. This is useful when two collections contain distinct objects that should be paired by a derived key rather than by object identity.

Parameters:

Name Type Description Default
source Iterable[Any]

Source elements to map from.

required
dest Iterable[Any]

Destination elements to map onto.

required
base_func Callable[[Any], Any]

Function that extracts the comparison key from both source and destination elements.

required

Returns:

Type Description
Dict[Any, Any]

Mapping from each source element to its corresponding destination element.

Raises:

Type Description
ValueError

If two destination elements produce the same baseline value.

ValueError

If a source element has no destination element with a matching baseline value.

Examples:

source = ["x0", "y0"]
dest = ["x1", "y1"]
matchby(source, dest, lambda item: item[0])
Source code in src/qten/utils/collections_ext.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def matchby(
    source: Iterable[Any], dest: Iterable[Any], base_func: Callable[[Any], Any]
) -> Dict[Any, Any]:
    """
    Map elements from source to destination using a provided mapping function.

    For each element in `source`, `base_func` is evaluated and matched against
    exactly one element in `dest` with the same baseline value. This is useful
    when two collections contain distinct objects that should be paired by a
    derived key rather than by object identity.

    Parameters
    ----------
    source : Iterable[Any]
        Source elements to map from.
    dest : Iterable[Any]
        Destination elements to map onto.
    base_func : Callable[[Any], Any]
        Function that extracts the comparison key from both source and
        destination elements.

    Returns
    -------
    Dict[Any, Any]
        Mapping from each source element to its corresponding destination
        element.

    Raises
    ------
    ValueError
        If two destination elements produce the same baseline value.
    ValueError
        If a source element has no destination element with a matching baseline
        value.

    Examples
    --------
    ```python
    source = ["x0", "y0"]
    dest = ["x1", "y1"]
    matchby(source, dest, lambda item: item[0])
    ```
    """
    mapping: Dict[Any, Any] = {}

    source_base: Dict[Any, Any] = {m: base_func(m) for m in source}
    dest_base: Dict[Any, Any] = {base_func(m): m for m in dest}

    if len(dest_base) != len(tuple(dest)):
        raise ValueError("Destination elements have non-unique base values!")

    for sm, sb in source_base.items():
        if sb not in dest_base:
            raise ValueError(
                f"Source element {sm} with base {sb} has no match in destination!"
            )
        mapping[sm] = dest_base[sb]

    return mapping