pyderive3 0.0.7__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyderive/__init__.py +60 -0
- pyderive/abc.py +204 -0
- pyderive/compat.py +245 -0
- pyderive/compile.py +362 -0
- pyderive/dataclasses.py +429 -0
- pyderive/extensions/README.md +5 -0
- pyderive/extensions/__init__.py +10 -0
- pyderive/extensions/serde/README.md +142 -0
- pyderive/extensions/serde/__init__.py +361 -0
- pyderive/extensions/serde/impl.py +122 -0
- pyderive/extensions/serde/serde.py +564 -0
- pyderive/extensions/serde/xml.py +288 -0
- pyderive/extensions/validate/README.md +83 -0
- pyderive/extensions/validate/__init__.py +199 -0
- pyderive/extensions/validate/generic.py +203 -0
- pyderive/extensions/validate/helpers.py +129 -0
- pyderive/extensions/validate/types.py +208 -0
- pyderive/extensions/validate/validators.py +666 -0
- pyderive/parse.py +157 -0
- pyderive/tests/__init__.py +16 -0
- pyderive/tests/dataclasses.py +156 -0
- pyderive/tests/extensions/__init__.py +15 -0
- pyderive/tests/extensions/serde.py +164 -0
- pyderive/tests/extensions/validate.py +289 -0
- pyderive3-0.0.7.dist-info/METADATA +189 -0
- pyderive3-0.0.7.dist-info/RECORD +28 -0
- pyderive3-0.0.7.dist-info/WHEEL +4 -0
- pyderive3-0.0.7.dist-info/licenses/LICENSE +21 -0
pyderive/compile.py
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
"""
|
|
2
|
+
DataClass Compiler Utilities
|
|
3
|
+
"""
|
|
4
|
+
from reprlib import recursive_repr
|
|
5
|
+
from types import FunctionType
|
|
6
|
+
from typing import Iterator, Tuple, Type, List, Optional, Any, Callable, Dict
|
|
7
|
+
|
|
8
|
+
from .abc import *
|
|
9
|
+
from .abc import ReprHide
|
|
10
|
+
|
|
11
|
+
#** Variables **#
|
|
12
|
+
__all__ = [
|
|
13
|
+
'POST_INIT',
|
|
14
|
+
'HDF',
|
|
15
|
+
'HDF_VAR',
|
|
16
|
+
|
|
17
|
+
'create_init',
|
|
18
|
+
'create_repr',
|
|
19
|
+
'create_compare',
|
|
20
|
+
'create_hash',
|
|
21
|
+
'create_iter',
|
|
22
|
+
'assign_func',
|
|
23
|
+
'gen_slots',
|
|
24
|
+
'add_slots',
|
|
25
|
+
'freeze_fields',
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
#:TODO: add unit-test for validator added with default/default-factory/frozen
|
|
29
|
+
|
|
30
|
+
#: post init function
|
|
31
|
+
POST_INIT = '__post_init__'
|
|
32
|
+
|
|
33
|
+
#: custom type to declare variable has a default factory
|
|
34
|
+
HDF = type('HAS_DEFAULT_FACTORY', (), {})
|
|
35
|
+
|
|
36
|
+
#: variable used to reference custom has-default-factory type
|
|
37
|
+
HDF_VAR = f'_{HDF.__name__}'
|
|
38
|
+
|
|
39
|
+
#** Functions **#
|
|
40
|
+
|
|
41
|
+
def _create_fn(
|
|
42
|
+
name: str,
|
|
43
|
+
args: List[str],
|
|
44
|
+
body: List[str],
|
|
45
|
+
locals: Optional[dict] = None,
|
|
46
|
+
globals: Optional[dict] = None,
|
|
47
|
+
return_type: Any = MISSING
|
|
48
|
+
):
|
|
49
|
+
"""create python function from specifications"""
|
|
50
|
+
locals = locals or {}
|
|
51
|
+
globals = globals or {}
|
|
52
|
+
# build code as string
|
|
53
|
+
return_anno = ''
|
|
54
|
+
if return_type is not MISSING:
|
|
55
|
+
locals['_return_type'] = return_type
|
|
56
|
+
return_anno = '->_return_type'
|
|
57
|
+
sargs = ','.join(args)
|
|
58
|
+
sbody = '\n'.join(f' {b}' for b in body)
|
|
59
|
+
func = f'def {name}({sargs}){return_anno}:\n{sbody}'
|
|
60
|
+
# compute function text as python object
|
|
61
|
+
exec(func, globals, locals)
|
|
62
|
+
return locals[name]
|
|
63
|
+
|
|
64
|
+
def _init_param(field: FieldDef) -> str:
|
|
65
|
+
"""generate field argument parameter"""
|
|
66
|
+
if field.default is MISSING and field.default_factory is MISSING:
|
|
67
|
+
default = ''
|
|
68
|
+
elif field.default is not MISSING:
|
|
69
|
+
default = f'=_init_{field.name}'
|
|
70
|
+
else:
|
|
71
|
+
default = f'={HDF_VAR}'
|
|
72
|
+
return f'{field.name}{default}'
|
|
73
|
+
|
|
74
|
+
def _init_value(field: FieldDef, globals: dict) -> str:
|
|
75
|
+
"""generate init field-value assignment"""
|
|
76
|
+
init_name = f'_init_{field.name}'
|
|
77
|
+
if field.default_factory is not MISSING:
|
|
78
|
+
if field.init:
|
|
79
|
+
globals[init_name] = field.default_factory
|
|
80
|
+
return f'{init_name}() if {field.name}' + \
|
|
81
|
+
f' is {HDF_VAR} else {field.name}'
|
|
82
|
+
else:
|
|
83
|
+
globals[init_name] = field.default_factory
|
|
84
|
+
return f'{init_name}()'
|
|
85
|
+
# no default factory
|
|
86
|
+
if field.init:
|
|
87
|
+
if field.default is not MISSING:
|
|
88
|
+
globals[init_name] = field.default
|
|
89
|
+
return field.name
|
|
90
|
+
# not default factory - is not init
|
|
91
|
+
if field.default is not MISSING:
|
|
92
|
+
globals[init_name] = field.default
|
|
93
|
+
return init_name
|
|
94
|
+
raise TypeError(f'field {field.name!r} has no default value')
|
|
95
|
+
|
|
96
|
+
def _init_assign(self_name: str, name: str, value: str, frozen: bool) -> str:
|
|
97
|
+
"""generate field variable assignment"""
|
|
98
|
+
if frozen:
|
|
99
|
+
return f'object.__setattr__({self_name}, {name!r}, {value})'
|
|
100
|
+
return f'{self_name}.{name}={value}'
|
|
101
|
+
|
|
102
|
+
def _init_validator(self_name: str,
|
|
103
|
+
field: FieldDef, value: str, globals: dict) -> Tuple[List[str], str]:
|
|
104
|
+
"""generate field validator function call"""
|
|
105
|
+
field_name = f'_field_{field.name}'
|
|
106
|
+
validator = f'_validate_{field.name}'
|
|
107
|
+
globals[field_name] = field
|
|
108
|
+
globals[validator] = field.validator
|
|
109
|
+
# generate validators/value code
|
|
110
|
+
validators = []
|
|
111
|
+
if field.default_factory is not MISSING:
|
|
112
|
+
validators.append(f'{field.name}={value}')
|
|
113
|
+
value = field.name
|
|
114
|
+
validators += [f'{value}={validator}({self_name}, {field_name}, {value})']
|
|
115
|
+
return validators, value
|
|
116
|
+
|
|
117
|
+
def create_init(
|
|
118
|
+
fields: Fields,
|
|
119
|
+
kw_only: bool = False,
|
|
120
|
+
post_init: bool = False,
|
|
121
|
+
frozen: bool = False,
|
|
122
|
+
) -> Callable:
|
|
123
|
+
"""
|
|
124
|
+
generate dynamic init-function from the following args/kwargs
|
|
125
|
+
|
|
126
|
+
:param fields: ordered field used to generate init-args/func-body
|
|
127
|
+
:param kw_only: override kw-only to make everything kw-only
|
|
128
|
+
:param post_init: enable post-init when true
|
|
129
|
+
:return: generated init-function made from specifications
|
|
130
|
+
"""
|
|
131
|
+
self_name = 'self'
|
|
132
|
+
locals: Dict[str, Any] = {}
|
|
133
|
+
globals: Dict[str, Any] = {HDF_VAR: HDF}
|
|
134
|
+
args, post, body, validators, kwonly = ['self'], [], [], [], []
|
|
135
|
+
for field in fields:
|
|
136
|
+
# handle non-init edge cases
|
|
137
|
+
name = field.name
|
|
138
|
+
if not field.init and not has_default(field):
|
|
139
|
+
# raise an error if field is an init-var
|
|
140
|
+
if field.field_type == FieldType.INIT_VAR:
|
|
141
|
+
raise TypeError(f'field {name!r} must have init as InitVar')
|
|
142
|
+
continue
|
|
143
|
+
# build parameter code
|
|
144
|
+
param = _init_param(field)
|
|
145
|
+
value = _init_value(field, globals)
|
|
146
|
+
if field.init:
|
|
147
|
+
if kw_only or field.kw_only:
|
|
148
|
+
kwonly.append(param)
|
|
149
|
+
else:
|
|
150
|
+
args.append(param)
|
|
151
|
+
# build validator function when enabled
|
|
152
|
+
if field.validator is not None:
|
|
153
|
+
if not callable(field.validator):
|
|
154
|
+
raise TypeError(f'field {name!r} validator is not callable')
|
|
155
|
+
validator, value = _init_validator(self_name, field, value, globals)
|
|
156
|
+
validators.extend(validator)
|
|
157
|
+
# track init-vars for later generation
|
|
158
|
+
if field.field_type == FieldType.INIT_VAR:
|
|
159
|
+
if field.default_factory is not MISSING:
|
|
160
|
+
raise TypeError(
|
|
161
|
+
f'init field {name!r} cannot have a default factory')
|
|
162
|
+
post.append(name)
|
|
163
|
+
continue
|
|
164
|
+
# build body code
|
|
165
|
+
assign = _init_assign(self_name, name, value, frozen or field.frozen)
|
|
166
|
+
body.append(assign)
|
|
167
|
+
# ensure body exists
|
|
168
|
+
if validators:
|
|
169
|
+
body = [*validators, *body]
|
|
170
|
+
if post_init:
|
|
171
|
+
params = ', '.join(post)
|
|
172
|
+
body.append(f'self.{POST_INIT}({params})')
|
|
173
|
+
if not body:
|
|
174
|
+
body.append('pass')
|
|
175
|
+
# generate function args/kwargs
|
|
176
|
+
if kwonly:
|
|
177
|
+
args.append('*')
|
|
178
|
+
args.extend(kwonly)
|
|
179
|
+
return _create_fn('__init__', args, body, locals, globals)
|
|
180
|
+
|
|
181
|
+
def _stdfields(fields: Fields) -> Iterator[FieldDef]:
|
|
182
|
+
"""retrieve only standard fields from fields-list"""
|
|
183
|
+
return (f for f in fields if f.field_type == FieldType.STANDARD)
|
|
184
|
+
|
|
185
|
+
def create_repr(fields: Fields, hide: Optional[ReprHide] = None) -> Callable:
|
|
186
|
+
"""
|
|
187
|
+
generate simple repr-function for the following field-structure
|
|
188
|
+
|
|
189
|
+
:param fields: ordered field used to generate repr-func
|
|
190
|
+
:param hide: optional hide setting for repr
|
|
191
|
+
:param return: repr-function
|
|
192
|
+
"""
|
|
193
|
+
body = ['f=[]']
|
|
194
|
+
for field in fields:
|
|
195
|
+
name = field.name
|
|
196
|
+
attr = f'self.{name}'
|
|
197
|
+
f_hide = field.metadata.get('hide') or hide
|
|
198
|
+
if f_hide == 'null':
|
|
199
|
+
prefix = ' '
|
|
200
|
+
body.append(f'if {attr} is not None:')
|
|
201
|
+
elif f_hide == 'empty':
|
|
202
|
+
body.append(f'if {attr} is not None'
|
|
203
|
+
f' and (not hasattr({attr}, "__len__") or len({attr}) != 0):')
|
|
204
|
+
prefix = ' ' if f_hide is not None else ''
|
|
205
|
+
body.append(f'{prefix}f.append("{name}=" + repr({attr}))')
|
|
206
|
+
body.append('return self.__class__.__qualname__ + "(" + ", ".join(f) + ")"')
|
|
207
|
+
func = _create_fn('__repr__', ['self'], body)
|
|
208
|
+
return recursive_repr('...')(func)
|
|
209
|
+
|
|
210
|
+
def _tuple_str(params: List[str], prefix: Optional[str] = None) -> str:
|
|
211
|
+
"""generate tuple string for the given params"""
|
|
212
|
+
if not params:
|
|
213
|
+
return '()'
|
|
214
|
+
items = (f'{prefix}.{param}' for param in params) if prefix else params
|
|
215
|
+
return '(' + ', '.join(items) + ',)'
|
|
216
|
+
|
|
217
|
+
def create_compare(fields: Fields, func: str, op: str) -> Callable:
|
|
218
|
+
"""
|
|
219
|
+
generate compare function w/ the following function name/operation
|
|
220
|
+
|
|
221
|
+
:param fields: ordered fields used to generate compare-func
|
|
222
|
+
:param func: function name string
|
|
223
|
+
:param op: function compare operation
|
|
224
|
+
:return: compare-function
|
|
225
|
+
"""
|
|
226
|
+
names = [f.name for f in _stdfields(fields) if f.compare]
|
|
227
|
+
self_t = _tuple_str(names, 'self')
|
|
228
|
+
other_t = _tuple_str(names, 'other')
|
|
229
|
+
return _create_fn(func, ['self', 'other'], [
|
|
230
|
+
'if other.__class__ is self.__class__:',
|
|
231
|
+
f' return {self_t} {op} {other_t}',
|
|
232
|
+
'return NotImplemented',
|
|
233
|
+
])
|
|
234
|
+
|
|
235
|
+
def create_hash(fields: Fields) -> Callable:
|
|
236
|
+
"""
|
|
237
|
+
generate hash-function for hashable fields
|
|
238
|
+
|
|
239
|
+
:param fields: ordered fields used to generate hash-function
|
|
240
|
+
:return: hash-function
|
|
241
|
+
"""
|
|
242
|
+
names = [f.name for f in _stdfields(fields)
|
|
243
|
+
if (f.compare if f.hash is None else f.hash)]
|
|
244
|
+
names_t = _tuple_str(names, 'self')
|
|
245
|
+
return _create_fn('__hash__', ['self'], [f'return hash({names_t})'])
|
|
246
|
+
|
|
247
|
+
def create_iter(fields: Fields) -> Callable:
|
|
248
|
+
"""
|
|
249
|
+
generate iter-function to iterate over all fields
|
|
250
|
+
|
|
251
|
+
:param fields: ordered fields used to generate iter-function
|
|
252
|
+
:return: iter-function
|
|
253
|
+
"""
|
|
254
|
+
names = [f.name for f in _stdfields(fields) if f.iter]
|
|
255
|
+
names_t = _tuple_str(names, 'self')
|
|
256
|
+
return _create_fn('__iter__', ['self'], [f'return iter({names_t})'])
|
|
257
|
+
|
|
258
|
+
def assign_func(cls: Type, func: Callable,
|
|
259
|
+
name: Optional[str] = None, overwrite: bool = False) -> bool:
|
|
260
|
+
"""
|
|
261
|
+
assign function to the object and modify qualname
|
|
262
|
+
|
|
263
|
+
:param cls: class object to assign to
|
|
264
|
+
:param func: function to assign to value
|
|
265
|
+
:param name: name of function to assign
|
|
266
|
+
:param overwrite: allow for overwrite if enabled
|
|
267
|
+
:return: true if object already exists else false
|
|
268
|
+
"""
|
|
269
|
+
name = name or func.__name__
|
|
270
|
+
if not overwrite and name in cls.__dict__:
|
|
271
|
+
return True
|
|
272
|
+
if isinstance(func, FunctionType):
|
|
273
|
+
func.__qualname__ = f'{cls.__qualname__}.{func.__name__}'
|
|
274
|
+
setattr(cls, name, func)
|
|
275
|
+
return False
|
|
276
|
+
|
|
277
|
+
def gen_slots(cls: Type, fields: Fields) -> Tuple[str, ...]:
|
|
278
|
+
"""
|
|
279
|
+
generate slots for fields connected to the given class object
|
|
280
|
+
|
|
281
|
+
WARNING: gen-slots cannot be applied to already generated
|
|
282
|
+
class objects. only during evaluation by a meta-class
|
|
283
|
+
or something similar. WHEN UNSURE USE ADD_SLOTS INSTEAD
|
|
284
|
+
|
|
285
|
+
:param cls: class-object to assign slots onto
|
|
286
|
+
:param fields: field structure to control slot definition
|
|
287
|
+
:return: tuple of slots for dataclass
|
|
288
|
+
"""
|
|
289
|
+
fields = list(_stdfields(fields))
|
|
290
|
+
if '__slots__' in cls.__dict__:
|
|
291
|
+
raise TypeError(f'{cls.__name__} already specifies __slots__')
|
|
292
|
+
# ensure slots don't overlap with bases-classes
|
|
293
|
+
slots = [f.name for f in fields]
|
|
294
|
+
bases = cls.__mro__[1:-1]
|
|
295
|
+
base_slots = {s for b in bases for s in getattr(b, '__slots__', [])}
|
|
296
|
+
return tuple([s for s in slots if s not in base_slots])
|
|
297
|
+
|
|
298
|
+
def add_slots(cls: TypeT, fields: Fields, frozen: bool = False) -> TypeT:
|
|
299
|
+
"""
|
|
300
|
+
attach slots for fields connected to the given class object
|
|
301
|
+
|
|
302
|
+
:param cls: class-object to assign slots onto
|
|
303
|
+
:param fields: field structure to control slot definition
|
|
304
|
+
:param frozen: apply additional methods when handing a frozen object
|
|
305
|
+
:return: updated class object
|
|
306
|
+
"""
|
|
307
|
+
fields = list(_stdfields(fields))
|
|
308
|
+
cls_dict = dict(cls.__dict__)
|
|
309
|
+
if '__slots__' in cls_dict:
|
|
310
|
+
raise TypeError(f'{cls.__name__} already specifies __slots__')
|
|
311
|
+
# ensure slots don't overlap with bases-classes and assign to dict
|
|
312
|
+
slots = [f.name for f in fields]
|
|
313
|
+
bases = cls.__mro__[1:-1]
|
|
314
|
+
base_slots = {s for b in bases for s in getattr(b, '__slots__', [])}
|
|
315
|
+
cls_dict['__slots__'] = tuple([s for s in slots if s not in base_slots])
|
|
316
|
+
# remove elements from dict before creation
|
|
317
|
+
cls_dict.pop('__dict__', None)
|
|
318
|
+
cls_dict.pop('__weakref__', None)
|
|
319
|
+
for name in slots:
|
|
320
|
+
cls_dict.pop(name, None)
|
|
321
|
+
# recreate class object w/ slots
|
|
322
|
+
qname = getattr(cls, '__qualname__', None)
|
|
323
|
+
cls = type(cls)(cls.__name__, cls.__bases__, cls_dict) #type: ignore
|
|
324
|
+
if qname is not None:
|
|
325
|
+
cls.__qualname__ = qname
|
|
326
|
+
# implement custom state functions when frozen to enable proper pickling
|
|
327
|
+
if frozen or any(f.frozen for f in fields):
|
|
328
|
+
names_t = _tuple_str([repr(name) for name in slots])
|
|
329
|
+
values_t = _tuple_str(slots, 'self')
|
|
330
|
+
getstate = _create_fn('__getstate__', ['self'], [f'return {values_t}'])
|
|
331
|
+
setstate = _create_fn('__setstate__', ['self', 'state'], [
|
|
332
|
+
f'for name, value in zip({names_t}, state):',
|
|
333
|
+
f' object.__setattr__(self, name, value)'
|
|
334
|
+
])
|
|
335
|
+
assign_func(cls, getstate)
|
|
336
|
+
assign_func(cls, setstate)
|
|
337
|
+
return cls
|
|
338
|
+
|
|
339
|
+
def freeze_fields(cls: Type, fields: Fields, frozen: bool = False):
|
|
340
|
+
"""
|
|
341
|
+
add custom __setattr__/__delattr__ funcs to prevent field modification
|
|
342
|
+
|
|
343
|
+
:param cls: class object to assign functions to
|
|
344
|
+
:param fields: field structure to control frozen status
|
|
345
|
+
:param frozen: override field frozen status
|
|
346
|
+
"""
|
|
347
|
+
fnames = [repr(f.name) for f in _stdfields(fields) if frozen or f.frozen]
|
|
348
|
+
names = _tuple_str(fnames)
|
|
349
|
+
globals = {'cls': cls, 'FrozenInstanceError': FrozenInstanceError}
|
|
350
|
+
ifstmt = f'if name in {names}:'
|
|
351
|
+
setattr = _create_fn('__setattr__', ['self', 'name', 'value'], [
|
|
352
|
+
ifstmt,
|
|
353
|
+
' raise FrozenInstanceError(f"cannot assign to field {name!r}")',
|
|
354
|
+
'super(cls, self).__setattr__(name, value)'
|
|
355
|
+
], globals=globals)
|
|
356
|
+
delattr = _create_fn('__delattr__', ['self', 'name'], [
|
|
357
|
+
ifstmt,
|
|
358
|
+
' raise FrozenInstanceError(f"cannot delete field {name!r}")',
|
|
359
|
+
'super(cls, self).__delattr__(name)'
|
|
360
|
+
], globals=globals)
|
|
361
|
+
assign_func(cls, setattr)
|
|
362
|
+
assign_func(cls, delattr)
|