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
19 changes: 19 additions & 0 deletions src/metaclass_registry/descendants.py
Original file line number Diff line number Diff line change
@@ -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)
29 changes: 29 additions & 0 deletions tests/test_descendants.py
Original file line number Diff line number Diff line change
@@ -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,)
Loading