-
Notifications
You must be signed in to change notification settings - Fork 2
/
better_abc.py
46 lines (31 loc) · 1.1 KB
/
better_abc.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
41
42
43
44
45
46
from abc import abstractmethod, ABCMeta as NativeABCMeta
abstract_method = abstractmethod
def abstract_property(function):
return property(abstractmethod(function))
class DummyAttribute:
pass
def abstract_attribute(obj=None):
if obj is None:
obj = DummyAttribute()
obj.__is_abstract_attribute__ = True
return obj
class ABCMeta(NativeABCMeta):
def __call__(cls, *args, **kwargs):
instance = 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):
pass
__all__ = ['abstract_method', 'abstract_property', 'abstract_attribute', 'ABCMeta', 'ABC']