Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/metaclass_registry/own_declarations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""Declarations each class states in its own body, read along the class's MRO."""

from __future__ import annotations

from collections.abc import Iterable, Iterator


class OwnDeclarations:
"""A class reads what each of its bases declared for itself under one attribute name.

Inheritance answers "the nearest declaration"; these answer "every class's own
declaration", the question a capability composed through several parents asks.
"""

@classmethod
def own_declarations(cls, name: str, bases: Iterable[type] | None = None) -> Iterator[tuple[type, object]]:

Check failure on line 16 in src/metaclass_registry/own_declarations.py

View workflow job for this annotation

GitHub Actions / code-quality

ruff (E501)

src/metaclass_registry/own_declarations.py:16:101: E501 Line too long (111 > 100)
"""Each base, in MRO order unless ``bases`` gives another order or scope, with the
value it declares in its own body; bases that declare nothing are skipped."""
for base in cls.__mro__ if bases is None else bases:
if name in base.__dict__:
yield base, base.__dict__[name]

@classmethod
def declared_items(cls, name: str, bases: Iterable[type] | None = None) -> Iterator[object]:
"""Every item of every base's own declared collection, in that order."""
for _, declared in cls.own_declarations(name, bases):
yield from declared

@classmethod
def declared_union(cls, name: str, bases: Iterable[type] | None = None) -> tuple[object, ...]:
"""The declared items, each once, nearest declaration first."""
return tuple(dict.fromkeys(cls.declared_items(name, bases)))
27 changes: 27 additions & 0 deletions tests/test_own_declarations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""A class reads every base's own declaration along its MRO, skipping bases that state none."""

from metaclass_registry.own_declarations import OwnDeclarations


class Root(OwnDeclarations):
keys = ("a",)


class Left(Root):
keys = ("b", "a")


class Right(Root):
pass


class Both(Left, Right):
keys = ("c",)


def test_own_declarations_follow_the_mro_and_skip_silent_bases() -> None:
assert [base for base, _ in Both.own_declarations("keys")] == [Both, Left, Root]
assert tuple(Both.declared_items("keys")) == ("c", "b", "a", "a")
assert Both.declared_union("keys") == ("c", "b", "a")
assert Both.declared_union("keys", reversed(Both.__mro__)) == ("a", "b", "c")
assert Both.declared_union("missing") == ()
Loading