Repository navigation
Expand file tree
/
Copy pathhelpers.py
More file actions
352 lines (291 loc) · 12.8 KB
/
Copy pathhelpers.py
File metadata and controls
352 lines (291 loc) · 12.8 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
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# Authors: Sylvain MARIE <sylvain.marie@se.com>
# + All contributors to <https://github.com/smarie/python-pyfields>
#
# License: 3-clause BSD, <https://github.com/smarie/python-pyfields/blob/master/LICENSE>
import sys
from copy import copy, deepcopy
from inspect import getmro, isclass
try:
from typing import Union, Type, TypeVar
T = TypeVar('T')
except ImportError:
pass
from pyfields.core import Field, ClassFieldAccessError, PY36, get_type_hints
class NotAFieldError(TypeError):
""" Raised by `get_field` when the class member with that name is not a field """
__slots__ = 'name', 'cls'
def __init__(self, cls, name):
self.name = name
self.cls = cls
def get_field(cls, name):
"""
Utility method to return the field member with name `name` in class `cls`.
If the member is not a field, a `NotAFieldError` is raised.
:param cls:
:param name:
:return:
"""
try:
member = getattr(cls, name)
except ClassFieldAccessError as e:
# we know it is a field :)
return e.field
except Exception:
# any other exception that can happen with a descriptor for example
raise NotAFieldError(cls, name)
else:
# it is a field if is it an instance of Field
if isinstance(member, Field):
return member
else:
raise NotAFieldError(cls, name)
def yield_fields(cls,
include_inherited=True, # type: bool
remove_duplicates=True, # type: bool
ancestors_first=True, # type: bool
public_only=False, # type: bool
_auto_fix_fields=False # type: bool
):
"""
Similar to `get_fields` but as a generator.
:param cls:
:param include_inherited:
:param remove_duplicates:
:param ancestors_first:
:param public_only:
:param _auto_fix_fields:
:return:
"""
# List the classes where we should be looking for fields
if include_inherited:
where_cls = reversed(getmro(cls)) if ancestors_first else getmro(cls)
else:
where_cls = (cls,)
# Init
_already_found_names = set() if remove_duplicates else None # a reference set of already yielded field names
_cls_pep484_member_type_hints = None # where to hold found type hints if needed
_all_fields_for_cls = None # temporary list when we have to reorder
# finally for each class, gather all fields in order
for _cls in where_cls:
if not PY36:
# in python < 3.6 we'll need to sort the fields at the end as class member order is not preserved
_all_fields_for_cls = []
elif _auto_fix_fields:
# in python >= 3.6, pep484 type hints can be available as member annotation, grab them
_cls_pep484_member_type_hints = get_type_hints(_cls)
for member_name in vars(_cls):
# if not member_name.startswith('__'): not stated in the doc: too dangerous to have such implicit filter
# avoid infinite recursion as this method is called in the descriptor for __init__
if not member_name == '__init__':
try:
field = get_field(_cls, member_name)
except NotAFieldError:
continue
if _auto_fix_fields:
# take this opportunity to set the name and type hints
field.set_as_cls_member(_cls, member_name, owner_cls_type_hints=_cls_pep484_member_type_hints)
if public_only and member_name.startswith('_'):
continue
if remove_duplicates:
if member_name in _already_found_names:
continue
else:
_already_found_names.add(member_name)
# maybe the field is overridden, in that case we should directly yield the new one
if _cls is not cls:
try:
overridden_field = get_field(cls, member_name)
except NotAFieldError:
overridden_field = None
else:
overridden_field = None
# finally yield it...
if PY36: # ...immediately in recent python versions because order is correct already
yield field if overridden_field is None else overridden_field
else: # ...or wait for this class to be collected, because the order needs to be fixed
_all_fields_for_cls.append((field, overridden_field))
if not PY36:
# order is random in python < 3.6 - we need to explicitly sort according to instance creation number
_all_fields_for_cls.sort(key=lambda f: f[0].__fieldinstcount__)
for field, overridden_field in _all_fields_for_cls:
yield field if overridden_field is None else overridden_field
def has_fields(cls,
include_inherited=True # type: bool
):
"""
Returns True if class `cls` defines at least one `pyfields` field.
If `include_inherited` is `True` (default), the method will return `True` if at least a field is defined in the
class or one of its ancestors. If `False`, the fields need to be defined on the class itself.
:param cls:
:param include_inherited:
:return:
"""
return any(yield_fields(cls, include_inherited=include_inherited))
if sys.version_info >= (3, 7):
ODict = dict
else:
from collections import OrderedDict
ODict = OrderedDict
def get_field_values(obj,
include_inherited=True, # type: bool
remove_duplicates=True, # type: bool
ancestors_first=True, # type: bool
public_only=False, # type: bool
container_type=ODict, # type: Type[T]
_auto_fix_fields=False # type: bool
):
"""
Utility method to collect all field names and values defined on an object, including all inherited or not.
By default duplicates are removed and ancestor fields are included and appear first. If a field is overridden,
it will appear at the position of the overridden field in the order.
The result is an ordered dictionary (a `dict` in python 3.7, an `OrderedDict` otherwise) of {name: value} pairs.
One can change the container type with the `container_type` attribute though, that will receive an iterable of
(key, value) pairs.
:param obj:
:param include_inherited:
:param remove_duplicates:
:param ancestors_first:
:param public_only:
:param container_type:
:param _auto_fix_fields:
:return:
"""
fields_gen = yield_fields(obj.__class__, include_inherited=include_inherited, public_only=public_only,
remove_duplicates=remove_duplicates, ancestors_first=ancestors_first,
_auto_fix_fields=_auto_fix_fields)
return container_type((f.name, getattr(obj, f.name)) for f in fields_gen)
def safe_isclass(obj # type: object
):
# type: (...) -> bool
"""Ignore any exception via isinstance on Python 3."""
try:
return isclass(obj)
except Exception:
return False
def get_fields(cls_or_obj,
include_inherited=True, # type: bool
remove_duplicates=True, # type: bool
ancestors_first=True, # type: bool
public_only=False, # type: bool
container_type=tuple, # type: Type[T]
_auto_fix_fields=False # type: bool
):
# type: (...) -> T
"""
Utility method to collect all fields defined in a class, including all inherited or not, in definition order.
By default duplicates are removed and ancestor fields are included and appear first. If a field is overridden,
it will appear at the position of the overridden field in the order.
If an object is provided, `get_fields` will be executed on its class.
:param cls_or_obj:
:param include_inherited:
:param remove_duplicates:
:param ancestors_first:
:param public_only:
:param container_type:
:param _auto_fix_fields:
:return: the fields (by default, as a tuple)
"""
if not safe_isclass(cls_or_obj):
cls_or_obj = cls_or_obj.__class__
return container_type(yield_fields(cls_or_obj, include_inherited=include_inherited, public_only=public_only,
remove_duplicates=remove_duplicates, ancestors_first=ancestors_first,
_auto_fix_fields=_auto_fix_fields))
# def ordered_dir(cls,
# ancestors_first=False # type: bool
# ):
# """
# since `dir` does not preserve order, lets have our own implementation
#
# :param cls:
# :param ancestors_first:
# :return:
# """
# classes = reversed(getmro(cls)) if ancestors_first else getmro(cls)
#
# for _cls in classes:
# for k in vars(_cls):
# yield k
def copy_value(val,
deep=True, # type: bool
autocheck=True # type: bool
):
"""
Returns a default value factory to be used in a `field(default_factory=...)`.
That factory will create a copy of the provided `val` everytime it is called. Handy if you wish to use mutable
objects as default values for your fields ; for example lists.
:param val: the (mutable) value to copy
:param deep: by default deep copies will be created. You can change this behaviour by setting this to `False`
:param autocheck: if this is True (default), an initial copy will be created when the method is called, so as to
alert the user early if this leads to errors.
:return:
"""
if deep:
if autocheck:
try:
# autocheck: make sure that we will be able to create copies later
deepcopy(val)
except Exception as e:
raise ValueError("The provided default value %r can not be deep-copied: caught error %r" % (val, e))
def create_default(obj):
return deepcopy(val)
else:
if autocheck:
try:
# autocheck: make sure that we will be able to create copies later
copy(val)
except Exception as e:
raise ValueError("The provided default value %r can not be copied: caught error %r" % (val, e))
def create_default(obj):
return copy(val)
# attach a method to easily get a new factory with a new value
def get_copied_value():
return val
def clone_with_new_val(newval):
return copy_value(newval, deep)
create_default.get_copied_value = get_copied_value
create_default.clone_with_new_val = clone_with_new_val
return create_default
def copy_field(field_or_name, # type: Union[str, Field]
deep=True # type: bool
):
"""
Returns a default value factory to be used in a `field(default_factory=...)`.
That factory will create a copy of the value in the given field. You can provide a field or a field name, in which
case this method is strictly equivalent to `copy_attr`.
:param field_or_name: the field or name of the field for which the value needs to be copied
:param deep: by default deep copies will be created. You can change this behaviour by setting this to `False`
:return:
"""
if isinstance(field_or_name, Field):
if field_or_name.name is None:
# Name not yet available, we'll get it later
if deep:
def create_default(obj):
return deepcopy(getattr(obj, field_or_name.name))
else:
def create_default(obj):
return copy(getattr(obj, field_or_name.name))
return create_default
else:
# use the field name
return copy_attr(field_or_name.name, deep=deep)
else:
# this is already a field name
return copy_attr(field_or_name, deep=deep)
def copy_attr(attr_name, # type: str
deep=True # type: bool
):
"""
Returns a default value factory to be used in a `field(default_factory=...)`.
That factory will create a copy of the value in the given attribute.
:param attr_name: the name of the attribute for which the value will be copied
:param deep: by default deep copies will be created. You can change this behaviour by setting this to `False`
:return:
"""
if deep:
def create_default(obj):
return deepcopy(getattr(obj, attr_name))
else:
def create_default(obj):
return copy(getattr(obj, attr_name))
return create_default