Skip to content

Base collections

base_collections

Generic dict- and list-like pydantic RootModel base classes.

BaseDict

Bases: RootModel[dict[str, T]]

__getitem__

Python
__getitem__(key: str) -> T

Get an item in the dictionary with the specified key.

Source code in src/stochas/base_collections.py
Python
def __getitem__(self, key: str) -> T:
    """Get an item in the dictionary with the specified key."""
    if key not in self.root:
        msg = f"'{key}' not found."
        logger.error(msg)
        raise KeyError(msg)
    return self.root[key]

__setitem__

Python
__setitem__(key: str, value: T) -> None

Set the value of a single key-value pair.

Source code in src/stochas/base_collections.py
Python
def __setitem__(self, key: str, value: T) -> None:
    """Set the value of a single key-value pair."""
    name = getattr(value, "name", None)
    if key != name:
        msg = f"Key '{key}' must match name '{name}'"
        logger.error(msg)
        raise ValueError(msg)
    self.update(value)

__iter__

Python
__iter__() -> Iterator[str]

Create an iterable object.

Source code in src/stochas/base_collections.py
Python
def __iter__(self) -> Iterator[str]:  # pyright: ignore[reportIncompatibleMethodOverride]
    """Create an iterable object."""
    return self.root.__iter__()

__len__

Python
__len__() -> int

Returns the number of elements in the dictionary.

Source code in src/stochas/base_collections.py
Python
def __len__(self) -> int:
    """Returns the number of elements in the dictionary."""
    return self.root.__len__()

__delitem__

Python
__delitem__(key: str) -> None

Delete the item with the specified key.

Source code in src/stochas/base_collections.py
Python
def __delitem__(self, key: str) -> None:
    """Delete the item with the specified key."""
    if key not in self.root:
        msg = f"'{key}' not found."
        logger.error(msg)
        raise KeyError(msg)
    del self.root[key]

__contains__

Python
__contains__(key: object) -> bool

Specifies if a key already exists in the dictionary.

Source code in src/stochas/base_collections.py
Python
def __contains__(self, key: object) -> bool:
    """Specifies if a key already exists in the dictionary."""
    return self.root.__contains__(key)

__reversed__

Python
__reversed__() -> Iterator[str]

Iterates over the dictionary's keys in reverse insertion order.

Source code in src/stochas/base_collections.py
Python
def __reversed__(self) -> Iterator[str]:
    """Iterates over the dictionary's keys in reverse insertion order."""
    return reversed(self.root)

get

Python
get(key: str, default: T | None = None) -> T | None

Returns the value for key if it exists, otherwise default.

Source code in src/stochas/base_collections.py
Python
def get(self, key: str, default: T | None = None) -> T | None:
    """Returns the value for key if it exists, otherwise default."""
    return self.root.get(key, default)

pop

Python
pop(key: str, *default: T) -> T

Removes the specified key and returns the corresponding value. Raises KeyError if the key is not found and no default is given.

Source code in src/stochas/base_collections.py
Python
def pop(self, key: str, *default: T) -> T:
    """Removes the specified key and returns the corresponding value. Raises KeyError if the key is not found and no default is given."""
    if key not in self.root:
        if default:
            return default[0]
        msg = f"'{key}' not found."
        logger.error(msg)
        raise KeyError(msg)
    return self.root.pop(key)

popitem

Python
popitem() -> tuple[str, T]

Removes and returns the last inserted key-value pair as a tuple.

Source code in src/stochas/base_collections.py
Python
def popitem(self) -> tuple[str, T]:
    """Removes and returns the last inserted key-value pair as a tuple."""
    return self.root.popitem()

clear

Python
clear() -> None

Removes all items from the dictionary.

Source code in src/stochas/base_collections.py
Python
def clear(self) -> None:
    """Removes all items from the dictionary."""
    self.root.clear()

setdefault

Python
setdefault(key: str, default: T) -> T

Returns the value for key if it exists, otherwise inserts default and returns it.

Source code in src/stochas/base_collections.py
Python
def setdefault(self, key: str, default: T) -> T:
    """Returns the value for key if it exists, otherwise inserts default and returns it."""
    if key in self.root:
        return self.root[key]
    self[key] = default
    return default

keys

Python
keys()

Returns the keys in the dictionary.

Source code in src/stochas/base_collections.py
Python
def keys(self):
    """Returns the keys in the dictionary."""
    return self.root.keys()

values

Python
values()

Returns the values in the dictionary.

Source code in src/stochas/base_collections.py
Python
def values(self):
    """Returns the values in the dictionary."""
    return self.root.values()

items

Python
items()

Returns the key-value pairs in the dictionary as tuples.

Source code in src/stochas/base_collections.py
Python
def items(self):
    """Returns the key-value pairs in the dictionary as tuples."""
    return self.root.items()

update

Python
update(value: T) -> None

Add a new dictionary key value pair. The key cannot already exist in the dictionary.

Source code in src/stochas/base_collections.py
Python
def update(self, value: T) -> None:
    """Add a new dictionary key value pair. The key cannot already exist in the dictionary."""
    name = getattr(value, "name", None)
    if name in self.root:
        msg = f"{name} has already been registered."
        logger.error(msg)
        raise KeyError(msg)

    self.force_update(value=value, warn=False)

update_many

Python
update_many(values: Iterable[T]) -> None

Add many new dictionary key value pair. The keys cannot already exist in the dictionary.

Source code in src/stochas/base_collections.py
Python
def update_many(self, values: Iterable[T]) -> None:
    """Add many new dictionary key value pair. The keys cannot already exist in the dictionary."""
    for value in values:
        self.update(value=value)

force_update

Python
force_update(value: T, warn: bool = True) -> None

Forces a key-value pair into the dictionary. Overwrites existing key if it exists.

Source code in src/stochas/base_collections.py
Python
def force_update(self, value: T, warn: bool = True) -> None:
    """Forces a key-value pair into the dictionary. Overwrites existing key if it exists."""
    name = getattr(value, "name")
    if warn:
        logger.warning(f"Forcing {name} into {self.__class__.__name__}.")
    self.root[name] = value

force_update_many

Python
force_update_many(
    values: Iterable[T], warn: bool = True
) -> None

Forces adding many new dictionary key value pair. Overwrites existing keys if they exist.

Source code in src/stochas/base_collections.py
Python
def force_update_many(self, values: Iterable[T], warn: bool = True) -> None:
    """Forces adding many new dictionary key value pair. Overwrites existing keys if they exist."""
    for value in values:
        self.force_update(value=value, warn=warn)

BaseList

Bases: RootModel[list[T]]

__len__

Python
__len__() -> int

Returns the number of elements in the list.

Source code in src/stochas/base_collections.py
Python
def __len__(self) -> int:
    """Returns the number of elements in the list."""
    return self.root.__len__()

__iter__

Python
__iter__() -> Iterator[T]

Create an iterable object.

Source code in src/stochas/base_collections.py
Python
def __iter__(self) -> Iterator[T]:  # pyright: ignore[reportIncompatibleMethodOverride]
    """Create an iterable object."""
    return self.root.__iter__()

__reversed__

Python
__reversed__() -> Iterator[T]

Iterates over the list in reverse order.

Source code in src/stochas/base_collections.py
Python
def __reversed__(self) -> Iterator[T]:
    """Iterates over the list in reverse order."""
    return reversed(self.root)

__contains__

Python
__contains__(value: object) -> bool

Specifies if a value already exists in the list.

Source code in src/stochas/base_collections.py
Python
def __contains__(self, value: object) -> bool:
    """Specifies if a value already exists in the list."""
    return self.root.__contains__(value)

__getitem__

Python
__getitem__(index: int) -> T
Python
__getitem__(index: slice) -> list[T]
Python
__getitem__(index: int | slice) -> T | list[T]

Gets the items in the specified index/indices.

Source code in src/stochas/base_collections.py
Python
def __getitem__(self, index: int | slice) -> T | list[T]:
    """Gets the items in the specified index/indices."""
    return self.root[index]

__setitem__

Python
__setitem__(index: int, value: T) -> None

Set the object at an index.

Source code in src/stochas/base_collections.py
Python
def __setitem__(self, index: int, value: T) -> None:
    """Set the object at an index."""
    self.root[index] = value

__delitem__

Python
__delitem__(index: int) -> None

Delete an element from the list.

Source code in src/stochas/base_collections.py
Python
def __delitem__(self, index: int) -> None:
    """Delete an element from the list."""
    del self.root[index]

append

Python
append(value: T) -> None

Append an item to the list.

Source code in src/stochas/base_collections.py
Python
def append(self, value: T) -> None:
    """Append an item to the list."""
    self.root.append(value)

extend

Python
extend(values: Iterable[T]) -> None

Append many items to the list.

Source code in src/stochas/base_collections.py
Python
def extend(self, values: Iterable[T]) -> None:
    """Append many items to the list."""
    self.root.extend(values)

__add__

Python
__add__(other: BaseList[T] | list[T]) -> Self

Returns a new list with the contents of both lists concatenated.

Source code in src/stochas/base_collections.py
Python
def __add__(self, other: BaseList[T] | list[T]) -> Self:
    """Returns a new list with the contents of both lists concatenated."""
    other_values = other.root if isinstance(other, BaseList) else other
    return self.__class__(root=[*self.root, *other_values])

__iadd__

Python
__iadd__(other: BaseList[T] | list[T]) -> Self

Extends the list in place with the contents of another list.

Source code in src/stochas/base_collections.py
Python
def __iadd__(self, other: BaseList[T] | list[T]) -> Self:
    """Extends the list in place with the contents of another list."""
    self.extend(other.root if isinstance(other, BaseList) else other)
    return self

pop

Python
pop(index: int = -1) -> T

Remove and return item at index (default last).

Source code in src/stochas/base_collections.py
Python
def pop(self, index: int = -1) -> T:
    """Remove and return item at index (default last)."""
    return self.root.pop(index)

insert

Python
insert(index: int, value: T) -> None

Insert an item before the given index.

Source code in src/stochas/base_collections.py
Python
def insert(self, index: int, value: T) -> None:
    """Insert an item before the given index."""
    self.root.insert(index, value)

remove

Python
remove(value: T) -> None

Remove the first occurrence of a value.

Source code in src/stochas/base_collections.py
Python
def remove(self, value: T) -> None:
    """Remove the first occurrence of a value."""
    self.root.remove(value)

clear

Python
clear() -> None

Remove all items from the list.

Source code in src/stochas/base_collections.py
Python
def clear(self) -> None:
    """Remove all items from the list."""
    self.root.clear()

index

Python
index(
    value: T, start: int = 0, stop: int | None = None
) -> int

Return the index of the first occurrence of a value.

Source code in src/stochas/base_collections.py
Python
def index(self, value: T, start: int = 0, stop: int | None = None) -> int:
    """Return the index of the first occurrence of a value."""
    if stop is None:
        stop = len(self.root)
    return self.root.index(value, start, stop)

count

Python
count(value: T) -> int

Return the number of occurrences of a value.

Source code in src/stochas/base_collections.py
Python
def count(self, value: T) -> int:
    """Return the number of occurrences of a value."""
    return self.root.count(value)

reverse

Python
reverse() -> None

Reverse the list in place.

Source code in src/stochas/base_collections.py
Python
def reverse(self) -> None:
    """Reverse the list in place."""
    self.root.reverse()

sort

Python
sort(
    *,
    key: Callable[[T], SupportsRichComparison]
    | None = None,
    reverse: bool = False,
) -> None

Sort the list in place.

Source code in src/stochas/base_collections.py
Python
def sort(
    self,
    *,
    key: Callable[[T], SupportsRichComparison] | None = None,
    reverse: bool = False,
) -> None:
    """Sort the list in place."""
    cast("list[Any]", self.root).sort(key=key, reverse=reverse)

find_by_name

Python
find_by_name(name: str) -> T

Utility to find a specific named value within the list.

Source code in src/stochas/base_collections.py
Python
def find_by_name(self, name: str) -> T:
    """Utility to find a specific named value within the list."""
    for item in self.root:
        item_name = getattr(item, "name", None)
        if item_name == name:
            return item
    msg = f"Item '{name}' not found in list."
    logger.error(msg)
    raise KeyError(msg)

HasUnitsCollection

Mixin for BaseDict subclasses whose items carry unit: UnitDescriptor | str | None. Provides a single shared update_unit_system implementation so DistributionDict, DesignValueDict, and NamedValueDict do not each repeat the same loop.

update_unit_system

Python
update_unit_system(us: UnitSystem) -> None

Re-resolves UnitDescriptor conversion factors for every item whose unit field is a UnitDescriptor (plain-string labels are left untouched).

Source code in src/stochas/base_collections.py
Python
def update_unit_system(self, us: UnitSystem) -> None:
    """Re-resolves UnitDescriptor conversion factors for every item whose `unit` field is a UnitDescriptor (plain-string labels are left untouched)."""
    for item in self.values():  # pyright: ignore[reportAttributeAccessIssue]
        if isinstance(item.unit, UnitDescriptor):
            item.unit = us.__getattr__(item.unit.name)