π οΈ Utilsο
Utility classes and helper data structures used throughout the package.
- class phyloom.utils.IndexedSet(items: Iterable[T] = ())[source]ο
-
A set that supports integer indexing and sequence-style iteration.
Membership checks, insertion, removal, and integer indexing take expected constant time.
- Parameters:
items β Initial items to insert into the set.
Examples
Maintain an indexed set of strings.
>>> from phyloom.utils import IndexedSet >>> items = IndexedSet(["a", "b", "c"]) >>> items[1], list(items) ('b', ['a', 'b', 'c']) >>> "b" in items, "d" in items (True, False) >>> len(items) 3
Adding an already-present item does not change the set.
>>> items.add("a") >>> list(items) ['a', 'b', 'c']
Removing an item may move the final item into its position, so the order of the remaining items is not preserved.
>>> items.remove("a") >>> items[:] ['c', 'b']
- class phyloom.utils.MetadataMixin(*args: Any, metadata: Metadata | None = None, **kwargs: Any)[source]ο
Mixin for objects that carry arbitrary metadata.
Metadata is stored as key-value pairs and can be accessed through explicit methods such as
set(),get(), andupdate(), or with item syntax.- Parameters:
metadata β Initial metadata to store.
Examples
Maintain arbitrary metadata for an object using the mixin.
>>> from typing import Any >>> from phyloom.utils import MetadataMixin >>> class Store(MetadataMixin): ... def __init__(self, **kwargs: Any): ... super().__init__(metadata=kwargs) >>> store = Store(state="S", time=0.0) >>> dict(store.metadata) {'state': 'S', 'time': 0.0} >>> store.set("state", "I") >>> store["state"] 'I' >>> store["time"] = 1.5 >>> store.get("time") 1.5 >>> store.update({"host": "human", "state": "R"}) >>> store.get("state") 'R' >>> store.get("missing", "fallback") 'fallback' >>> "state" in store True >>> dict(store.metadata) {'state': 'R', 'time': 1.5, 'host': 'human'} >>> store.delete("host") >>> "host" in store False >>> store.clear() >>> dict(store.metadata) {}
- update(metadata: Metadata)[source]ο
Update multiple metadata values from a mapping of key-value pairs.
- class phyloom.utils.PriorityBuckets(items: Iterable[tuple[KT, VT]] = ())[source]ο
Bases:
Generic[KT,VT]A minimum-priority queue that groups values with equal keys.
Each key identifies one bucket, and bucket values are kept in insertion order. Adding to an existing key and peeking at the smallest key takes constant time; adding a new key and removing the smallest key take logarithmic time in the number of keys.
- Parameters:
items β Initial key-value pairs to insert.
Examples
Maintain a priority queue of buckets with integer keys and string values.
>>> from phyloom.utils import PriorityBuckets >>> buckets = PriorityBuckets([(2, "second"), (1, "first")]) >>> buckets.push(1, "also first") >>> buckets.peek_key() 1 >>> len(buckets) 2 >>> buckets.pop() ['first', 'also first'] >>> len(buckets), buckets.pop() (1, ['second'])
- push(key: KT, value: VT)[source]ο
Add a value to the bucket for a key, creating the bucket if necessary.
- copy() PriorityBuckets[KT, VT][source]ο
Return a shallow copy of the queue.
- class phyloom.utils.Registry(name: str, base_type: type[BaseModelT], discriminator: str = 'spec')[source]ο
Bases:
Generic[BaseModelT]Registry for polymorphic Pydantic configuration models.
A registry maps string discriminator keys to subclasses of a
pydantic.BaseModel. It can load a mapping into the corresponding registered class, or expose the same behavior as apydantic.BeforeValidatorthroughvalidatorfor an annotated configuration field.- Parameters:
name β Human-readable name used in registry errors.
base_type β Base model class that every registered class must extend.
discriminator β Input field containing the registration key.
Examples
Register a concrete Pydantic model under a discriminator key, retrieve the registered class, and load configured model instances.
>>> from typing import Annotated >>> from pydantic import BaseModel >>> from phyloom.utils import Registry >>> class Plugin(BaseModel): ... kind: str = "plugin" >>> registry = Registry("plugin", Plugin, "name") >>> @registry.register("demo") ... class DemoPlugin(Plugin): ... data: int = 1 >>> registry.get("demo") is DemoPlugin True >>> loaded = registry.load({"name": "demo", "data": 3}) >>> type(loaded) is DemoPlugin True >>> loaded.kind, loaded.data ('plugin', 3) >>> existing = DemoPlugin(data=2) >>> registry.load(existing) is existing True
Use the validator in an annotated Pydantic field to load registered models during validation.
>>> class Config(BaseModel): ... plugin: Annotated[Plugin, registry.validator] >>> configured = Config.model_validate( ... {"plugin": {"name": "demo", "data": 4}} ... ) >>> type(configured.plugin) is DemoPlugin True >>> configured.plugin.kind, configured.plugin.data ('plugin', 4)
- register(key: str) Callable[[RegisteredT], RegisteredT][source]ο
Return a decorator that registers a model class under
key.The decorated class must inherit from the registryβs base type, and each key may be registered only once.
- load(value: object) BaseModelT[source]ο
Load a registered model from a mapping or return an existing one.
For mappings, the discriminator field selects the concrete class and is removed before Pydantic validates the remaining fields. Existing instances of the registryβs base type are returned unchanged.
- property validator: BeforeValidatorο
Pydantic validator that loads a registered model from a mapping or returns an existing instance, backed by
load().