πŸ› οΈ Utils

Utility classes and helper data structures used throughout the package.

class phyloom.utils.IndexedSet(items: Iterable[T] = ())[source]

Bases: Sequence[T], Set[T]

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']
add(item: T)[source]

Add an item unless it is already present.

discard(item: T)[source]

Remove an item if it is present.

remove(item: T)[source]

Remove an item.

__contains__(item: object) → bool[source]

Return whether an item is present.

__len__() → int[source]

Return the number of items.

__iter__() → Iterator[T][source]

Iterate over items in their current indexed order.

__getitem__(index: int) → T[source]
__getitem__(index: slice) → list[T]

Return an item by index or a list of items for a slice.

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(), and update(), 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)
{}
property metadata: Metadata

Read-only view of the stored metadata.

set(key: str, value: Any)[source]

Set one metadata value by key.

update(metadata: Metadata)[source]

Update multiple metadata values from a mapping of key-value pairs.

get(key: str, default: Any | None = None) → Any[source]

Return one metadata value by key, or a default if the key is not present.

delete(key: str)[source]

Delete one metadata value by key.

clear()[source]

Remove all metadata.

__getitem__(key: str) → Any[source]

Return one metadata value with item syntax.

__setitem__(key: str, value: Any)[source]

Set one metadata value with item syntax.

__delitem__(key: str)[source]

Delete one metadata value with item syntax.

__contains__(key: str) → bool[source]

Return whether a metadata key is present.

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.

peek_key() → KT[source]

Return the smallest key without removing its bucket.

pop() → list[VT][source]

Remove the smallest-key bucket and return its values.

copy() → PriorityBuckets[KT, VT][source]

Return a shallow copy of the queue.

__bool__() → bool[source]

Return whether the queue contains at least one key.

__len__() → int[source]

Return the number of keys in 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 a pydantic.BeforeValidator through validator for 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.

keys() → list[str][source]

Return the registered discriminator keys in registration order.

get(key: str) → type[BaseModelT][source]

Return the registered model class for key.

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().

__len__() → int[source]

Return the number of registered model classes.

class phyloom.utils.SetView(s: Set[T])[source]

Bases: Set[T]

A read-only, live view of an abstract set.

Parameters:

s – Set to wrap.

__contains__(x: object) → bool[source]

Return whether an item is present in the wrapped set.

__iter__() → Iterator[T][source]

Iterate over the wrapped set.

__len__() → int[source]

Return the number of items in the wrapped set.