-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShowCaseClassContract.py
48 lines (37 loc) · 1.29 KB
/
ShowCaseClassContract.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
47
48
from contract import Case, contract
class NamedListMeta(type):
def __new__(mcs, name, bases, ns: dict):
if ns.get('_root'):
return super().__new__(mcs, name, bases, ns)
annotations = ns.get('__annotations__')
if not annotations:
def __init__(self):
pass
else:
annotations = tuple(annotations)
def __init__(self: list, *args, **kwargs):
data = {**dict(zip(annotations, args)), **kwargs}
try:
for attr in annotations:
self.append(data[attr])
except KeyError:
raise ValueError(f"Field {attr!r} is not specified!")
def __repr__(self):
return '{}[{}]'.format(
name, ', '.join(f'{attr}={self[idx]}'
for idx, attr in enumerate(annotations)))
bases = tuple(each for each in bases if each is not NamedList)
if list not in bases:
bases = (*bases, list)
cls = type(name, bases, ns)
cls.__init__ = __init__
cls.__repr__ = __repr__
return cls
class NamedList(metaclass=NamedListMeta):
_root = True
@contract(Case)
class MyT(NamedList):
a: int
b: int
c: int
d: int