From 1ab9979a04044d590f9532450c18fe777bfeaac5 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 16 Nov 2026 16:08:09 -0500 Subject: [PATCH] Descendants: a class family's members from the class graph The Textual fork walked __subclasses__ by hand twice (DOMNode.contexts and Component.named). One mixin owns the walk: depth first, declaration order, each class once. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gZLdupVQyBzHTmHBC9Cyn --- src/metaclass_registry/descendants.py | 19 ++++++++++++++++++ tests/test_descendants.py | 29 +++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 src/metaclass_registry/descendants.py create mode 100644 tests/test_descendants.py 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,)