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
2 changes: 2 additions & 0 deletions src/metaclass_registry/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,39 +7,41 @@

__version__ = "0.4.1"

from .cache import RegistryCacheManager
from .core import (
PRIMARY_KEY,
REPLACES_REGISTERED_ATTRIBUTE,
AutoRegisterMeta,
LazyDiscoveryDict,
RegisteredEnumMeta,
RegistryConfig,
RegistryFamily,
RegistryKeyAttribute,
SecondaryRegistry,
SecondaryRegistryDict,
extract_key_from_backend_suffix,
extract_key_from_class_name,
extract_key_from_handler_suffix,
is_same_declaration,
make_suffix_extractor,
register_once,
)
from .discovery import (
discover_registry_classes,
discover_registry_classes_recursive,
import_module_preserving_root_logging,
)
from .exceptions import (
CacheError,
DiscoveryError,
DuplicateRegistryKeyError,
RegistryError,
)
from .abstract_hooks import AbstractHooksMeta
from .mro_dispatch import MroDispatch, handles

Check failure on line 41 in src/metaclass_registry/__init__.py

View workflow job for this annotation

GitHub Actions / code-quality

ruff (I001)

src/metaclass_registry/__init__.py:10:1: I001 Import block is un-sorted or un-formatted help: Organize imports

__all__ = [
"AbstractHooksMeta",
# Core
"AutoRegisterMeta",
"RegistryConfig",
Expand Down
27 changes: 27 additions & 0 deletions src/metaclass_registry/abstract_hooks.py
Original file line number Diff line number Diff line change
@@ -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)
)
34 changes: 34 additions & 0 deletions tests/test_abstract_hooks.py
Original file line number Diff line number Diff line change
@@ -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)
Loading