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
25 changes: 21 additions & 4 deletions src/metaclass_registry/mro_dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ class MroDispatch:
"""

_handler_declarations: ClassVar[tuple[tuple[str, tuple[type, ...]], ...]] = ()
_handler_names: ClassVar[dict[type, tuple[str, ...]]] = {}
DISCARD: ClassVar[object] = object()

def __init_subclass__(cls, **kwargs: Any) -> None:
Expand All @@ -45,14 +46,30 @@ def __init_subclass__(cls, **kwargs: Any) -> None:
for name, method in methods.items()
if (classes := getattr(method, "__handled_classes__", ()))
)
cls._handler_names = {}

@classmethod
def handler_names_for(cls, value_type: type) -> Iterator[str]:
"""Resolve a declaration directly; instance dispatch uses the same lookup."""
for capability in value_type.__mro__:
for name, classes in cls._handler_declarations:
if capability in classes:
yield name
return iter(cls.resolved_handler_names(value_type))

@classmethod
def resolved_handler_names(cls, value_type: type) -> tuple[str, ...]:
"""The handlers this consumer declares for a value type, most specific first.

The consumer's declarations and the value type's MRO are both fixed when their
classes are created, so the pair is resolved once and every dispatch reads it.
"""
try:
return cls._handler_names[value_type]
except KeyError:
names = cls._handler_names[value_type] = tuple(
name
for capability in value_type.__mro__
for name, classes in cls._handler_declarations
if capability in classes
)
return names

@classmethod
def handler_for(cls, value_type: type) -> Callable[..., Any]:
Expand Down
15 changes: 15 additions & 0 deletions tests/test_mro_dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,21 @@ def test_base_class_registration_catches_subclass_nodes() -> None:
assert list(NodeKinds.handler_names_for(ast.If)) == ["statement", "any_node"]


def test_a_subclass_resolves_its_own_handlers_after_its_parent_has() -> None:
assert list(NodeKinds.handler_names_for(ast.Return)) == ["return_", "statement", "any_node"]

class LoudKinds(NodeKinds):
@handles(ast.Return)
def shout(self, node: ast.Return) -> None:
self.seen.append("LOUD")

assert "shout" in LoudKinds.handler_names_for(ast.Return)
assert "shout" not in NodeKinds.handler_names_for(ast.Return)
loud = LoudKinds()
loud.dispatch_sync(ast.Return(value=None))
assert sorted(loud.seen) == ["AST", "LOUD", "Return", "stmt"]


def test_value_without_a_declared_handler_passes_through() -> None:
kinds = NodeKinds()
value = object()
Expand Down
Loading