diff --git a/src/metaclass_registry/mro_dispatch.py b/src/metaclass_registry/mro_dispatch.py index b473269..aa82f54 100644 --- a/src/metaclass_registry/mro_dispatch.py +++ b/src/metaclass_registry/mro_dispatch.py @@ -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: @@ -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]: diff --git a/tests/test_mro_dispatch.py b/tests/test_mro_dispatch.py index e11385b..a4f05ec 100644 --- a/tests/test_mro_dispatch.py +++ b/tests/test_mro_dispatch.py @@ -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()