diff --git a/src/metaclass_registry/descendants.py b/src/metaclass_registry/descendants.py new file mode 100644 index 0000000..7ed3f88 --- /dev/null +++ b/src/metaclass_registry/descendants.py @@ -0,0 +1,19 @@ +"""A class family's members, read from the class graph instead of a hand-kept registry.""" + +from __future__ import annotations + + +class Descendants: + """A class lists itself and every class below it, each once, depth first in the order + the subclasses were declared.""" + + @classmethod + def descendants(cls) -> tuple[type, ...]: + pending: list[type] = [cls] + found: dict[type, None] = {} + while pending: + owner = pending.pop() + if owner not in found: + found[owner] = None + pending.extend(reversed(owner.__subclasses__())) + return tuple(found) diff --git a/tests/test_descendants.py b/tests/test_descendants.py new file mode 100644 index 0000000..8a77ec1 --- /dev/null +++ b/tests/test_descendants.py @@ -0,0 +1,29 @@ +"""A class lists its whole family from the class graph, each member once, in declaration order.""" + +from metaclass_registry.descendants import Descendants + + +class Root(Descendants): + pass + + +class Left(Root): + pass + + +class Right(Root): + pass + + +class Both(Left, Right): + pass + + +class LeftLeaf(Left): + pass + + +def test_descendants_walk_depth_first_in_declaration_order_without_repeats() -> None: + assert Root.descendants() == (Root, Left, Both, LeftLeaf, Right) + assert Right.descendants() == (Right, Both) + assert LeftLeaf.descendants() == (LeftLeaf,)