diff --git a/src/metaclass_registry/__init__.py b/src/metaclass_registry/__init__.py index 3983a98..f42c9b3 100644 --- a/src/metaclass_registry/__init__.py +++ b/src/metaclass_registry/__init__.py @@ -37,9 +37,11 @@ DuplicateRegistryKeyError, RegistryError, ) +from .abstract_hooks import AbstractHooksMeta from .mro_dispatch import MroDispatch, handles __all__ = [ + "AbstractHooksMeta", # Core "AutoRegisterMeta", "RegistryConfig", diff --git a/src/metaclass_registry/abstract_hooks.py b/src/metaclass_registry/abstract_hooks.py new file mode 100644 index 0000000..95d5355 --- /dev/null +++ b/src/metaclass_registry/abstract_hooks.py @@ -0,0 +1,27 @@ +"""Abstract methods enforced without ABCMeta.""" + +from __future__ import annotations + +from typing import Any + + +class AbstractHooksMeta(type): + """A class whose MRO declares an abstract method it still resolves can't be built. + + ABCMeta does the same but replaces isinstance and issubclass, which doubles their + cost on every check. This reads the whole MRO once, at class creation, so a plain + mixin's abstract hooks count as well as a declared base's. Assigning + __abstractmethods__ sets the flag object.__new__ refuses on. + """ + + def __init__( + cls, name: str, bases: tuple[type, ...], namespace: dict[str, Any], **kwargs: Any + ) -> None: + super().__init__(name, bases, namespace, **kwargs) + cls.__abstractmethods__ = frozenset( + member + for base in cls.__mro__ + for member, value in vars(base).items() + if getattr(value, "__isabstractmethod__", False) + and getattr(getattr(cls, member, None), "__isabstractmethod__", False) + ) diff --git a/tests/test_abstract_hooks.py b/tests/test_abstract_hooks.py new file mode 100644 index 0000000..a6e6f05 --- /dev/null +++ b/tests/test_abstract_hooks.py @@ -0,0 +1,34 @@ +"""A class whose MRO still leaves an abstract hook unresolved cannot be built; a mixin's +hooks count as well as a declared base's.""" + +from abc import abstractmethod + +import pytest + +from metaclass_registry import AbstractHooksMeta + + +class Hook: + @abstractmethod + def answer(self) -> int: ... + + +class Contract(Hook, metaclass=AbstractHooksMeta): + pass + + +class Answered(Contract): + def answer(self) -> int: + return 1 + + +def test_an_unresolved_mixin_hook_refuses_construction() -> None: + assert Contract.__abstractmethods__ == frozenset({"answer"}) + with pytest.raises(TypeError): + Contract() + + +def test_a_resolved_hook_builds_and_isinstance_stays_plain() -> None: + assert Answered().answer() == 1 + assert type(Contract) is AbstractHooksMeta + assert isinstance(Answered(), Hook)