-
Notifications
You must be signed in to change notification settings - Fork 2
/
attr_property.py
270 lines (245 loc) · 9.26 KB
/
attr_property.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
260
261
262
263
264
265
266
267
268
269
270
"""Property support for attrs"""
from functools import partial
import attr
__version__ = "0.0.10"
def property_getter(self, name, getter=None, cache=False):
"""
Getter of the property
@params:
name (str): The name of the property
getter (callable): User-defined getter
cache (bool): Whether cache the results
"""
if cache and name in self.__attrs_property_cached__:
return self.__attrs_property_cached__[name]
raw = self.__attrs_property_raw__.get(name)
ret = getter(self, raw) \
if callable(getter) else raw
if cache:
self.__attrs_property_cached__[name] = ret
return ret
def property_setter(self, # pylint: disable=too-many-arguments
value,
name,
setter=None,
converter=None,
validator=None):
"""
Setter of the property
@params:
value (any): The value of the property
name (str): The name of the property
setter (callable): A post user-defined setter
converter (callable): The converter defined in attr_property
validator (callable): The validator defined in attr_property
"""
# remove the cached value
if name in self.__attrs_property_cached__:
del self.__attrs_property_cached__[name]
if converter:
value = converter(value)
if validator:
validator(self, attr.fields_dict(self.__class__)[name], value)
if setter:
value_set = setter(self, value)
if value_set is not None:
value = value_set
self.__attrs_property_raw__[name] = value
def property_deleter(self, name, deleter=None):
"""
Deleter of the property
@params:
name (str): The name of the property
deleter (callable): User-defined deleter
"""
if name in self.__attrs_property_raw__:
del self.__attrs_property_raw__[name]
if name in self.__attrs_property_cached__:
del self.__attrs_property_cached__[name]
if deleter:
deleter(self)
def _attrs_to_init_script(attrs, # pylint: disable=too-many-arguments
frozen,
slots,
post_init,
cache_hash,
base_attr_map,
is_exc):
"""Used to replace the function in attr._make to create __init__ function"""
# pragma: no cover
script, globs, annotations = attr._make._attrs_to_init_script(
attrs, frozen, slots, post_init, cache_hash, base_attr_map, is_exc)
if frozen:
return script, globs, annotations
lines = script.splitlines()
lines.insert(1, ' self.__attrs_property_cached__ = {}')
lines.insert(2, ' self.__attrs_property_raw__ = {}')
return '\n'.join(lines), globs, annotations
def _make_init(cls, attrs, post_init, frozen, slots, cache_hash, base_attr_map,
is_exc): # pragma: no cover
# pylint: disable=E,W,R,C
attrs = [a for a in attrs if a.init or a.default is not attr._make.NOTHING]
unique_filename = attr._make._generate_unique_filename(cls, "init")
script, globs, annotations = _attrs_to_init_script(attrs, frozen, slots,
post_init, cache_hash,
base_attr_map, is_exc)
locs = {}
bytecode = compile(script, unique_filename, "exec")
attr_dict = dict((a.name, a) for a in attrs)
globs.update({"NOTHING": attr._make.NOTHING, "attr_dict": attr_dict})
if frozen is True:
# Save the lookup overhead in __init__ if we need to circumvent
# immutability.
globs["_cached_setattr"] = object.__setattr__
eval(bytecode, globs, locs)
# In order of debuggers like PDB being able to step through the code,
# we add a fake linecache entry.
attr._make.linecache.cache[unique_filename] = (
len(script),
None,
script.splitlines(True),
unique_filename,
)
__init__ = locs["__init__"]
__init__.__annotations__ = annotations
return __init__
attr._make._make_init = _make_init
def attr_property_class(cls):
"""
Extending attr.s with property support
"""
if not hasattr(cls, '__attrs_attrs__'):
raise ValueError(
"attr_property_class should be a decorator "
"of an attr.s decorated class."
)
if hasattr(cls, '__slots__'):
cls_dict = {
key: val
for key, val in cls.__dict__.items() if key not in cls.__slots__
}
cls_dict['__slots__'] += ('__attrs_property_raw__',
'__attrs_property_cached__')
cls = type(cls)(cls.__name__, cls.__bases__, cls_dict)
for attribute in cls.__attrs_attrs__:
if attribute.metadata.get('property'):
attr_getter = partial(property_getter,
name=attribute.name,
getter=attribute.metadata['property.getter'],
cache=attribute.metadata['property.cache'])
attr_setter = partial(
property_setter,
name=attribute.name,
setter=attribute.metadata['property.setter'],
converter=(attribute.converter
if (attribute.converter
and attribute.metadata[
'property.converter_runtime'
])
else None),
validator=(attribute.validator
if (attribute.validator
and attribute.metadata[
'property.validator_runtime'
])
else None)
)
attr_deleter = partial(
property_deleter,
name=attribute.name,
deleter=attribute.metadata['property.deleter'])
setattr(cls,
attribute.name,
property(
attr_getter,
None
if attribute.metadata['property.setter'] is False
else attr_setter,
None
if attribute.metadata['property.deleter'] is False
else attr_deleter,
attribute.metadata['property.doc'] or (
attribute.metadata['property.getter'].__doc__
if attribute.metadata['property.getter']
else "Property {}".format(attribute.name)
)
))
if attribute.metadata['property.raw']:
setattr(
cls,
attribute.metadata['property.raw'] + attribute.name,
property(
# pylint: disable=cell-var-from-loop
lambda self, name=attribute.name: self.
__attrs_property_raw__[name]))
return cls
def attr_property( # pylint: disable=redefined-builtin,too-many-locals,too-many-arguments
default=attr.NOTHING,
validator=None,
repr=True,
cmp=None,
hash=None,
init=True,
metadata=None,
type=None,
converter=None,
factory=None,
kw_only=False,
eq=None,
order=None,
getter=None,
setter=None,
deleter=None, # property
validator_runtime=True,
converter_runtime=True,
cache=True,
raw=False,
doc=None
):
"""
Extending attr.ib
@params:
...: attr.ib params
getter (callable|NoneType): User defined getter
setter (callable|bool|NoneType): User defined setter
- None: Use default setter
- False: Disable setter
deleter: (callable|bool|NoneType): User defined deleter
- None: Use default deleter
- False: Disable deleter
validator_runtime (bool): Run validator in setter
converter_runtime (bool): Run converter in setter
cache (bool): Cache the value calculated in getter
raw (bool|str): Enable a property to get the raw value before
being calculated in getter.
- False: Disable this property
- True: Use '_' as prefix
- Otherwise the prefix.
@returns:
(attr.ib): attr.ib object with property metadata
"""
metadata = metadata or {}
metadata['property'] = True
metadata['property.getter'] = getter
metadata['property.setter'] = setter
metadata['property.deleter'] = deleter
metadata['property.validator_runtime'] = validator_runtime
metadata['property.converter_runtime'] = converter_runtime
metadata['property.cache'] = cache
metadata['property.raw'] = '_' if raw is True else raw
metadata['property.doc'] = doc
return attr.ib(
default=default,
validator=validator,
repr=repr,
cmp=cmp,
hash=hash,
init=init,
metadata=metadata,
type=type,
converter=converter,
factory=factory,
kw_only=kw_only,
eq=eq,
order=order,
)