Coverage for src/metaclass_registry/mro_dispatch.py: 97%
67 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 00:39 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 00:39 +0000
1"""Class-owned handlers, composed along the value's C3 MRO."""
3from __future__ import annotations
5from collections.abc import Callable, Iterable, Iterator
6from typing import Any, ClassVar, TypeVar
8Handler = TypeVar("Handler", bound=Callable[..., Any])
9Value = TypeVar("Value")
12def handles(*classes: type) -> Callable[[Handler], Handler]:
13 """Declare the nominal cases handled by a consumer method."""
15 def decorate(handler: Handler) -> Handler:
16 handler.__handled_classes__ = classes # type: ignore[attr-defined]
17 return handler
19 return decorate
22class MroDispatch:
23 """Invoke specific handlers before base handlers; consumer overrides win.
25 The method declarations are the authority. No global registry, registration
26 order, or event-name roster participates in dispatch. A diamond ancestor is
27 visited once by Python's MRO. A returned replacement flows to later handlers;
28 ``DISCARD`` ends the pipeline without returning a value to its caller.
29 """
31 _handler_declarations: ClassVar[tuple[tuple[str, tuple[type, ...]], ...]] = ()
32 _handler_names: ClassVar[dict[type, tuple[str, ...]]] = {}
33 DISCARD: ClassVar[object] = object()
35 def __init_subclass__(cls, **kwargs: Any) -> None:
36 super().__init_subclass__(**kwargs)
37 # Select effective declarations once, including unannotated overrides
38 # which suppress an inherited handler. Keep names rather than bound
39 # methods: each invocation still borrows its own instance's behavior.
40 methods: dict[str, Any] = {}
41 for owner in cls.__mro__:
42 for name, method in vars(owner).items():
43 methods.setdefault(name, method)
44 cls._handler_declarations = tuple(
45 (name, classes)
46 for name, method in methods.items()
47 if (classes := getattr(method, "__handled_classes__", ()))
48 )
49 cls._handler_names = {}
51 @classmethod
52 def handler_names_for(cls, value_type: type) -> Iterator[str]:
53 """Resolve a declaration directly; instance dispatch uses the same lookup."""
54 return iter(cls.resolved_handler_names(value_type))
56 @classmethod
57 def resolved_handler_names(cls, value_type: type) -> tuple[str, ...]:
58 """The handlers this consumer declares for a value type, most specific first.
60 The consumer's declarations and the value type's MRO are both fixed when their
61 classes are created, so the pair is resolved once and every dispatch reads it.
62 """
63 try:
64 return cls._handler_names[value_type]
65 except KeyError:
66 names = cls._handler_names[value_type] = tuple(
67 name
68 for capability in value_type.__mro__
69 for name, classes in cls._handler_declarations
70 if capability in classes
71 )
72 return names
74 @classmethod
75 def handler_for(cls, value_type: type) -> Callable[..., Any]:
76 """The most specific class-level handler declared for ``value_type``."""
77 handler: Callable[..., Any] = getattr(cls, next(cls.handler_names_for(value_type)))
78 return handler
80 def handlers_for(self, value: Any) -> Iterator[Callable[..., Any]]:
81 for name in self.handler_names_for(type(value)):
82 yield getattr(self, name)
84 async def dispatch(self, value: Value, *args: Any, **kwargs: Any) -> Value | None:
85 handlers = tuple(self.handlers_for(value))
86 if not handlers:
87 return value
88 return await self.consume_handlers(value, handlers, *args, **kwargs)
90 async def consume_handlers(
91 self,
92 value: Value,
93 handlers: Iterable[Handler],
94 *args: Any,
95 **kwargs: Any,
96 ) -> Value | None:
97 """Consume the selected declarations inside the consumer's resource lifetime."""
98 for handler in handlers:
99 replacement = await handler(value, *args, **kwargs)
100 if replacement is self.DISCARD:
101 return None
102 value = self.replace_value(value, replacement)
103 return value
105 def dispatch_sync(self, value: Value, *args: Any, **kwargs: Any) -> Value | None:
106 """Consume saved presentation facts without introducing an event loop."""
107 return self.consume_handlers_sync(value, self.handlers_for(value), *args, **kwargs)
109 def consume_handlers_sync(
110 self,
111 value: Value,
112 handlers: Iterable[Handler],
113 *args: Any,
114 **kwargs: Any,
115 ) -> Value | None:
116 for handler in handlers:
117 replacement = handler(value, *args, **kwargs)
118 if replacement is self.DISCARD:
119 return None
120 value = self.replace_value(value, replacement)
121 return value
123 @staticmethod
124 def replace_value(value: Value, replacement: Value | None) -> Value:
125 if replacement is None:
126 return value
127 if type(replacement) is not type(value):
128 raise TypeError("A dispatch replacement must preserve event identity")
129 return replacement