-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathidbase.py
More file actions
executable file
·152 lines (111 loc) · 4.28 KB
/
Copy pathidbase.py
File metadata and controls
executable file
·152 lines (111 loc) · 4.28 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#!/usr/bin/env python
# coding: utf-8
from collections import namedtuple
class IDBase(str):
_attrs = (
# ('server_id', 0, 12, ServerID),
# ('_non_attr', 12, 13, validator),
# ('mountpoint_index', 13, 16, MountPointIndex),
# ('port', 13, 16, _port),
)
_str_len = 0
_tostr_fmt = '' # '{attr_1}-{attr_2:0>3}'
def __new__(clz, *args, **kwargs):
if len(args) + len(kwargs) == 1:
# New from a single serialized string
s = (list(args) + kwargs.values())[0]
s = str(s)
return clz._new_by_str(s)
else:
# multi args: new by making an instance
return clz._new_by_attrs(*args, **kwargs)
@classmethod
def _new_by_attrs(clz, *args, **kwargs):
# Create a namedtuple to simplify arguments receiving
tuple_type = namedtuple('_' + clz.__name__,
' '.join([x[0]
for x in clz._attrs
if clz._is_key_attr(x)
]))
t = tuple_type(*args, **kwargs)
# warn: if the value is float and _tostr_fmt is with float format,
# raise ValueError. Not convert to string?
s = clz._tostr_fmt.format(**{k: str(v)
for k, v in t._asdict().items()})
return clz._new_by_str(s)
@classmethod
def _new_by_str(clz, s):
if len(s) != clz._str_len:
raise ValueError('Expected {clz} length'
' to be {l} but {sl}: {s}'.format(
clz=clz.__name__,
l=clz._str_len,
sl=len(s),
s=s))
return super(IDBase, clz).__new__(clz, s)
def _init_by_str(self):
id_attrs = []
clz = self.__class__
for ii, attr_definition in enumerate(clz._attrs):
k, start_idx, end_idx, attr_type, opt = clz._normalize(attr_definition)
# avoid repeated init, when accessing a key that does not exist
try:
if ii == 0:
return super(IDBase, self).__getattribute__(k)
except AttributeError:
pass
if opt['self']:
val = self
else:
val = attr_type(self[start_idx:end_idx])
if opt['embed']:
for a in val._id_base_attrs:
if not a.startswith('_'):
super(IDBase, self).__setattr__(a, getattr(val, a))
id_attrs.append(a)
if k.startswith('_'):
continue
super(IDBase, self).__setattr__(k, val)
id_attrs.append(k)
super(IDBase, self).__setattr__('_id_base_attrs', tuple(id_attrs))
@classmethod
def _is_key_attr(clz, attr_definition):
name, s, e, attr_type, opt = clz._normalize(attr_definition)
if name.startswith('_'):
return False
return opt['key_attr']
@classmethod
def _normalize(clz, attr_definition):
name, s, e, attr_type, opt = (attr_definition + (None,))[:5]
if opt is None:
opt = {}
elif opt is False:
opt = {'key_attr': False}
elif opt == 'self':
opt = {'key_attr': False, 'self': True}
elif opt == 'embed':
opt = {'embed': True}
else:
pass
tmpl = {'key_attr': True,
'self': False,
'embed': False,
}
tmpl.update(opt)
opt = tmpl
if opt['self']:
opt['key_attr'] = False
return name, s, e, attr_type, opt
def __setattr__(self, n, v):
raise TypeError('{clz} does not allow to change attribute'.format(
clz=self.__class__.__name__))
def __getattr__(self, n):
self._init_by_str()
return super(IDBase, self).__getattribute__(n)
def as_tuple(self):
lst = []
for attr_definition in self._attrs:
k = attr_definition[0]
if IDBase._is_key_attr(attr_definition):
lst.append(getattr(self, k))
return tuple(lst)