This repository has been archived by the owner on Oct 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
containers.py
259 lines (200 loc) · 6.96 KB
/
containers.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
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
"""Converter classes for abstract container types."""
from .. import common
from ..base.container import Container
from . import standard
log = common.logger(__name__)
class Dictionary(Container, dict):
"""Base class for a dictionary of attribute converters."""
@classmethod
def default(cls):
"""Create an uninitialized object."""
if cls is Dictionary:
msg = "Dictionary class must be subclassed to use"
raise NotImplementedError(msg)
return cls.__new__(cls)
@classmethod
def to_value(cls, data):
value = cls.default()
# Convert object attributes to a dictionary
attrs = common.ATTRS[cls].copy()
if isinstance(data, cls):
dictionary = {}
for k, v in data.items():
if k in attrs:
dictionary[k] = v
for k, v in data.__dict__.items():
if k in attrs:
dictionary[k] = v
else:
dictionary = to_dict(data)
# Map object attributes to converters
for name, data in dictionary.items():
try:
converter = attrs.pop(name)
except KeyError:
converter = standard.match(name, data, nested=True)
common.ATTRS[cls][name] = converter
# Convert the loaded data
if issubclass(converter, Container):
container = converter()
container.apply(data)
value[name] = container
else:
value[name] = converter.to_value(data)
# Create default values for unmapped converters
for name, converter in attrs.items():
if issubclass(converter, Container):
value[name] = converter()
else:
value[name] = converter.to_value(None)
log.warn("added missing nested key '%s'...", name)
return value
@classmethod
def to_data(cls, value):
value = cls.to_value(value)
data = {}
for name, converter in common.ATTRS[cls].items():
data[name] = converter.to_data(value.get(name, None))
return data
def apply(self, data):
# TODO: replace to_value and to_data
cls = self.__class__
# TODO: is `default` still needed?
value = cls.default()
# Convert object attributes to a dictionary
attrs = common.ATTRS[cls].copy()
if isinstance(data, cls):
dictionary = {}
for k, v in data.items():
if k in attrs:
dictionary[k] = v
for k, v in data.__dict__.items():
if k in attrs:
dictionary[k] = v
else:
dictionary = to_dict(data)
# Map object attributes to converters
for name, data in dictionary.items():
try:
converter = attrs.pop(name)
except KeyError:
converter = standard.match(name, data, nested=True)
common.ATTRS[cls][name] = converter
# Convert the loaded data
if issubclass(converter, Container):
container = getattr(self, name, None)
if not isinstance(container, converter):
container = converter.default()
setattr(self, name, container)
container.apply(data)
value[name] = container
else:
value[name] = converter.to_value(data)
# Create default values for unmapped converters
for name, converter in attrs.items():
if issubclass(converter, Container):
value[name] = converter()
else:
value[name] = converter.to_value(None)
log.warn("added missing nested key '%s'...", name)
self.clear()
self.update(value)
class List(Container, list):
"""Base class for a homogeneous list of attribute converters."""
ALL = 'all'
@common.classproperty
def item_type(cls): # pylint: disable=E0213
"""Get the converter class for all items."""
return common.ATTRS[cls].get(cls.ALL)
@classmethod
def default(cls):
"""Create an uninitialized object."""
if cls is List:
raise NotImplementedError("List class must be subclassed to use")
if not cls.item_type:
raise NotImplementedError("List subclass must specify item type")
return cls.__new__(cls)
@classmethod
def to_value(cls, data):
value = cls.default()
for item in to_list(data):
if issubclass(cls.item_type, Container):
container = cls.item_type.default() # pylint: disable=E1120
container.apply(item)
value.append(container)
else:
value.append(cls.item_type.to_value(item))
return value
@classmethod
def to_data(cls, value):
value = cls.to_value(value)
data = []
if value:
for item in value:
data.append(cls.item_type.to_data(item))
return data
def apply(self, data):
# TODO: replace to_value and to_data
cls = self.__class__
# TODO: is `default` still needed?
value = cls.default()
converter = cls.item_type
for item in to_list(data):
if issubclass(converter, Container):
try:
container = self[len(value)]
except IndexError:
container = converter.default() # pylint: disable=E1120
else:
if not isinstance(container, converter):
container = converter.default() # pylint: disable=E1120
container.apply(item)
value.append(container)
else:
value.append(converter.to_value(item))
self[:] = value[:]
def to_dict(obj):
"""Convert a dictionary-like object to a dictionary.
>>> to_dict({'key': 42})
{'key': 42}
>>> to_dict("key=42")
{'key': '42'}
>>> to_dict("key")
{'key': None}
>>> to_dict(None)
{}
"""
if isinstance(obj, dict):
return obj
elif isinstance(obj, str):
text = obj.strip()
parts = text.split('=')
if len(parts) == 2:
return {parts[0]: parts[1]}
else:
return {text: None}
else:
return {}
def to_list(obj):
"""Convert a list-like object to a list.
>>> to_list([1, 2, 3])
[1, 2, 3]
>>> to_list("a,b,c")
['a', 'b', 'c']
>>> to_list("item")
['item']
>>> to_list(None)
[]
"""
if isinstance(obj, list):
return obj
elif isinstance(obj, str):
text = obj.strip()
if ',' in text and ' ' not in text:
return text.split(',')
else:
return text.split()
elif obj is not None:
return [obj]
else:
return []