diff --git a/src/metaclass_registry/own_declarations.py b/src/metaclass_registry/own_declarations.py new file mode 100644 index 0000000..c52685b --- /dev/null +++ b/src/metaclass_registry/own_declarations.py @@ -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]]: + """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))) diff --git a/tests/test_own_declarations.py b/tests/test_own_declarations.py new file mode 100644 index 0000000..ac01e89 --- /dev/null +++ b/tests/test_own_declarations.py @@ -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") == ()