-
Notifications
You must be signed in to change notification settings - Fork 0
/
abstract_helpers.py
40 lines (34 loc) · 1.21 KB
/
abstract_helpers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from typing import cast, Any, Callable, TypeVar
from abc import ABCMeta as NativeABCMeta
from abc import abstractmethod, abstractproperty
R = TypeVar('R')
class DummyAttribute:
pass
def abstract_attribute(obj: Callable[[Any], R] | None = None) -> R:
_obj = cast(Any, obj)
if obj is None:
_obj = DummyAttribute()
_obj.__is_abstract_attribute__ = True
return cast(R, _obj)
class ABCMeta(NativeABCMeta):
def __call__(cls, *args : Any, **kwargs : Any) -> NativeABCMeta:
instance : NativeABCMeta = NativeABCMeta.__call__(cls, *args, **kwargs)
abstract_attributes = {
name
for name in dir(instance)
if getattr(getattr(instance, name), '__is_abstract_attribute__', False)
}
if abstract_attributes:
raise NotImplementedError(
"Can't instantiate abstract class {} with"
" abstract attributes: {}".format(
cls.__name__,
', '.join(abstract_attributes)
)
)
return instance
class ABC(metaclass=ABCMeta):
"""Helper class that provides a standard way to create an ABC using
inheritance.
"""
__slots__ = ()