abcreg 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
abcreg/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from abcreg.annotated_abc import AnnotatedABC, AnnotatedABCMeta
2
+
3
+ __all__ = ["AnnotatedABC", "AnnotatedABCMeta"]
abcreg/_annotations.py ADDED
@@ -0,0 +1,6 @@
1
+ try:
2
+ from annotationlib import get_annotations
3
+ except ImportError:
4
+ from inspect import get_annotations
5
+
6
+ __all__ = ["get_annotations"]
@@ -0,0 +1,64 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from abc import ABC, ABCMeta
5
+ from collections.abc import Callable
6
+ from typing import get_type_hints
7
+
8
+ __all__ = ["AnnotatedABC", "AnnotatedABCMeta"]
9
+
10
+
11
+ def _normalize_annotations(fn: Callable[..., object]) -> dict[str, object]:
12
+ module_name = getattr(fn, "__module__", None)
13
+ module = sys.modules.get(module_name) if module_name is not None else None
14
+ globalns = vars(module) if module is not None else {}
15
+ return get_type_hints(fn, globalns=globalns, localns=globalns)
16
+
17
+
18
+ def _has_fn(
19
+ impl: type,
20
+ abc: type,
21
+ name: str,
22
+ expected: dict[str, object],
23
+ ) -> bool:
24
+ skip = set(abc.__mro__)
25
+ for base in impl.__mro__:
26
+ if base in skip:
27
+ continue
28
+ for key, value in base.__dict__.items():
29
+ if key == name and _normalize_annotations(value) == expected:
30
+ return True
31
+ return False
32
+
33
+
34
+ class AnnotatedABCMeta(ABCMeta):
35
+ def register(cls, subclass: type) -> type:
36
+ cls._validate_implementation(subclass)
37
+ return super().register(subclass)
38
+
39
+ def _validate_implementation(cls, impl: type) -> None:
40
+ for name, expected in cls._abstract_annotations().items():
41
+ if not _has_fn(impl, cls, name, expected):
42
+ msg = (
43
+ f"{impl!r} does not fully implement {cls.__name__!r}: "
44
+ f"missing or mismatched {name!r}"
45
+ )
46
+ raise TypeError(msg)
47
+
48
+ def _abstract_annotations(cls) -> dict[str, dict[str, object]]:
49
+ methods: dict[str, dict[str, object]] = {}
50
+ for base in cls.__mro__:
51
+ if not isinstance(base, AnnotatedABCMeta):
52
+ continue
53
+ for name, value in base.__dict__.items():
54
+ if getattr(value, "__isabstractmethod__", False):
55
+ methods[name] = _normalize_annotations(value)
56
+ return methods
57
+
58
+
59
+ class AnnotatedABC(ABC, metaclass=AnnotatedABCMeta):
60
+ def __init_subclass__(cls, **kwargs: object) -> None:
61
+ super().__init_subclass__(**kwargs)
62
+ for base in cls.__bases__:
63
+ if isinstance(base, AnnotatedABCMeta):
64
+ base._validate_implementation(cls)
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: abcreg
3
+ Version: 0.1.0
4
+ Summary: Add your description here
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.13
8
+ Description-Content-Type: text/markdown
9
+
10
+ # ABCReg
11
+
12
+ ABCReg adds `AnnotatedABC` and `AnnotatedABCMeta`, which provide additional interface checking at registration time to ensure that registered virtual and ordinary subclasses are valid.
13
+
14
+ Use ABCReg if you are designing a plugin API or any other interface that might be implemented by an end user.
15
+
16
+ ## Defining the Interface
17
+
18
+ Use `AnnotatedABC` just like an ordinary `ABC`. Make sure to mark your API methods as abstract and provide type hints:
19
+
20
+ ```
21
+ from abc import abstractmethod
22
+ from abcreg import AnnotatedABC
23
+
24
+ class Queryable(AnnotatedABC):
25
+ @abstractmethod
26
+ def query(self, **kwargs) -> str: ...
27
+ ```
28
+
29
+ We recommend you use virtual inheritance:
30
+
31
+ ```
32
+ @Queryable.register(VirtualQueryProvider)
33
+ class VirtualQueryProvider:
34
+ def query(self, **kwargs) -> str:
35
+ return "query result"
36
+
37
+ assert issubclass(VirtualQueryProvider, Queryable)
38
+ assert isinstance(VirtualQueryProvider(), Queryable)
39
+ ```
40
+
41
+ But, regular inheritance will also work:
42
+
43
+ ```
44
+ class QueryProvider(Queryable):
45
+ def query(self, **kwargs) -> str:
46
+ return "query result"
47
+
48
+ assert issubclass(QueryProvider, Queryable)
49
+ ```
50
+
51
+ ## Requirements and Usage
52
+
53
+ Requries Python `3.10+`. With UV, require with `uv add abcreg`.
@@ -0,0 +1,7 @@
1
+ abcreg/__init__.py,sha256=1JEWr2wq1tgplAefagpPIHuqpmALZp0FI1-WhhK01Cs,112
2
+ abcreg/_annotations.py,sha256=XTx1JVn1GZvhMmX4470dszFkPiWHek0VabhFbRWuS_s,142
3
+ abcreg/annotated_abc.py,sha256=3OCn0UVJBvhPUp50P1WreRgBygHNAX6qXSnSI01dLuk,2202
4
+ abcreg-0.1.0.dist-info/METADATA,sha256=m4AzddYA0ht1YxFR0jf77_FJvYV_8lj6zr3csiY3Fq8,1398
5
+ abcreg-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
6
+ abcreg-0.1.0.dist-info/licenses/LICENSE,sha256=oWN3hgCPpp69WEgHXOML1NEDCYdp6SRmvMTEl0XK9ko,1068
7
+ abcreg-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Will Bowers
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.