/
properties.py
478 lines (374 loc) · 14.4 KB
/
properties.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
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
"""Specialized descriptors/properties for classes."""
from __future__ import annotations
import warnings
from typing import (Any, Callable, Generic, Optional, Sequence, Tuple, Type,
Union, cast, overload)
from housekeeping import deprecate_non_keyword_only_args
from typing_extensions import Self, TypeAlias, TypeVar
from djblets.deprecation import RemovedInDjblets50Warning
# NOTE: When mypy supports PEP 696, we can give many of these defaults.
# Setters can be based on the preceding getters as specific in
# Generic[...]. This will simplify usage for callers in the default
# case.
_StoredT = TypeVar('_StoredT')
_GetT = TypeVar('_GetT')
_SetT = TypeVar('_SetT')
_AliasPropertySetT = TypeVar('_AliasPropertySetT')
_AliasPropertyStoredT: TypeAlias = Any
_TypedPropertyGetT = TypeVar('_TypedPropertyGetT')
_TypedPropertyValidTypesParamT: TypeAlias = Union[Type[_SetT],
Sequence[Type[_SetT]]]
class BaseProperty(Generic[_StoredT]):
"""Base class for a custom property for a class.
This is an optional base class that provides handy utilities that
properties may need. For instance, being able to determine the name of
the property's attribute on a class.
Version Changed:
3.3:
This now supports generics for typing, taking the type of the stored
content.
"""
######################
# Instance variables #
######################
#: The name of the owning attribute.
#:
#: Version Added:
#: 3.3
attr_name: str
def get_attr_name(
self,
instance: object,
) -> str:
"""Return the name of this property's attribute.
Deprecated:
3.3:
This has been replaced with :py:attr:`attr_name`, and will be
removed in Djblets 5.0.
Args:
instance (object):
The instance owning this property.
Returns:
str:
The name of this property on the instance.
"""
RemovedInDjblets50Warning.warn(
'%s.get_attr_name() is deprecated. Please access the `attr_name` '
'attribute instead. This will be removed in Djblets 5.0.')
return self.attr_name
def __set_name__(
self,
owner: type,
name: str,
) -> None:
"""Handle setting the attribute name for this property.
Version Added:
3.3
Args:
owner (type, unused):
The class that owns the property.
name (str):
The attribute name for this property.
"""
self.attr_name = name
class AliasProperty(Generic[_GetT, _AliasPropertySetT],
BaseProperty[_AliasPropertyStoredT]):
"""A property that aliases to another property or attribute.
Alias properties are used to automatically retrieve from another property
on access, or to set a value on another property. It's useful when
wanting to rename an attribute but continue to provide a deprecated
version, or when creating an object that provides a set of compatibility
attributes for use with legacy code.
Alias properties can optionally emit a deprecation warning on use, in order
to help in the process of migrating legacy code.
Version Changed:
3.3:
This now supports generics for typing, taking the types to return on
access, and types that can be set.
Example:
.. code-block:: python
class MyClass:
new_prop: str
old_prop: AliasProperty[int, str] = AliasProperty[int, str](
'new_prop',
convert_to_func=str,
convert_from_func=int)
Note that the explicit type declaration is important. Without it,
type checkers may allow constructors to override the type.
"""
######################
# Instance variables #
######################
#: Whether to emit a deprecation warning on access.
deprecated: bool
#: The type of class to use for the deprecation warning.
deprecation_warning: Type[DeprecationWarning]
#: The name of the property or attribute to read from and write to
prop_name: str
@deprecate_non_keyword_only_args(RemovedInDjblets50Warning)
def __init__(
self,
prop_name: str,
*,
convert_to_func: Optional[Callable[[_AliasPropertySetT],
_AliasPropertyStoredT]] = None,
convert_from_func: Optional[Callable[[_AliasPropertyStoredT],
_GetT]] = None,
deprecated: bool = False,
deprecation_warning: Type[DeprecationWarning] = DeprecationWarning,
) -> None:
"""Initialize the property.
Version Changed:
3.3:
All arguments but ``prop_name`` must be provided as keyword
arguments. This will be enforced in Djblets 5.0.
Args:
prop_name (str):
The name of the property or attribute to read from and write
to.
convert_to_func (callable, optional):
An optional function to call on a value before setting it on
the aliased property name. This must take in the value as a
parameter and return a value to set.
convert_from_func (callable, optional):
An optional function to call on a value after accessing it on
the aliased property name and before returning to the caller.
This must take in the value from the aliased property and
return a value to return to the caller.
deprecated (bool, optional):
Whether to emit a deprecation warning when setting or accessing
the property.
deprecation_warning (type):
The type of class to use for the deprecation warning. This
should be a subclass of :py:class:`DeprecationWarning`.
"""
self.prop_name = prop_name
self.deprecated = deprecated
self.deprecation_warning = deprecation_warning
self._convert_to_func = convert_to_func
self._convert_from_func = convert_from_func
def __set__(
self,
instance: object,
value: _AliasPropertySetT,
) -> None:
"""Set a value on the property.
This will convert the value (if ``convert_to_func`` was provided
to this property) and set it on the aliased property.
If this is a deprecated property, this will emit a warning.
Args:
instance (object):
The instance owning this property.
value (object):
The value being set.
"""
if self.deprecated:
cls_name = type(instance).__name__
warnings.warn('%s.%s is deprecated. Please set %s.%s instead.'
% (cls_name, self.attr_name,
cls_name, self.prop_name),
self.deprecation_warning,
stacklevel=2)
if value is not None and self._convert_to_func is not None:
value = self._convert_to_func(value)
setattr(instance, self.prop_name, value)
@overload
def __get__(
self,
instance: None,
owner: Type[object],
) -> Self:
...
@overload
def __get__(
self,
instance: object,
owner: Type[object],
) -> _GetT:
...
def __get__(
self,
instance: object,
owner: Type[object],
) -> Union[Self, _GetT]:
"""Return the value of the property.
This will retrieve the value from the aliased property, converting
it (if ``convert_from_func`` was provided to this property), and
return it.
If this is a deprecated property, this will emit a warning.
Args:
instance (object):
The instance owning this property.
owner (type):
The instance's class.
Returns:
object:
The property value.
"""
if instance is None:
return self
if self.deprecated:
cls_name = type(instance).__name__
warnings.warn('%s.%s is deprecated. Please access %s.%s instead.'
% (cls_name, self.attr_name,
cls_name, self.prop_name),
self.deprecation_warning,
stacklevel=2)
value = getattr(instance, self.prop_name)
if value is not None and self._convert_from_func is not None:
value = self._convert_from_func(value)
return value
class TypedProperty(Generic[_TypedPropertyGetT, _SetT],
BaseProperty[_TypedPropertyGetT]):
"""A property that enforces type safety.
This property will ensure that only values that are compatible with a
given type can be set. This ensures type safety and helps catch errors
early.
Version Changed:
3.3:
This now supports generics for typing, taking the types to return on
access, and types that can be set.
Example:
.. code-block:: python
class MyClass:
optional_prop: TypedProperty[Optional[str], Optional[str]] = \
TypedProperty(str)
required_to_set_prop: TypedProperty[Optional[int], int] = \
TypedProperty(int,
default=None
allow_none=False)
never_none_prop: TypedProperty[int, int] = \
TypedProperty(int,
default=42,
allow_none=False)
Note that the explicit type declaration is important. Without it,
type checkers may allow constructors to override the type.
"""
######################
# Instance variables #
######################
#: Whether a ``None`` value is allowed to be set.
allow_none: bool
#: The default value for the property if one is not set.
default: Optional[_TypedPropertyGetT]
#: The types that are valid for this property.
#:
#: New values are checked against this at runtime.
valid_types: Tuple[Type[_SetT], ...]
@deprecate_non_keyword_only_args(RemovedInDjblets50Warning)
def __init__(
self,
valid_types: _TypedPropertyValidTypesParamT,
*,
default: Optional[_TypedPropertyGetT] = None,
allow_none: bool = True,
) -> None:
"""Initialize the property.
Version Changed:
3.3:
All arguments but ``prop_name`` must be provided as keyword
arguments. This will be enforced in Djblets 5.0.
Args:
valid_types (list of type):
The types of values that are permitted to be set.
default (object, optional):
The default value, if one is not set.
allow_none (bool, optional):
Whether ``None`` values are allowed to be set.
"""
if isinstance(valid_types, tuple):
self.valid_types = valid_types
elif isinstance(valid_types, Sequence):
self.valid_types = tuple(valid_types)
else:
self.valid_types = (valid_types,)
self.default = default
self.allow_none = allow_none
def __set__(
self,
instance: object,
value: _SetT,
) -> None:
"""Set a value on the property.
This will check if the value is of a valid type, and then set it on
the instance.
Args:
instance (object):
The instance owning this property.
value (object):
The value being set.
Raises:
TypeError:
The value is not of a valid type.
"""
if value is None and not self.allow_none:
raise TypeError('None is not a valid value for this property.')
if value is not None and not isinstance(value, self.valid_types):
raise TypeError('%s (%r) is not a valid type for this property.'
% (type(value).__name__, value))
instance.__dict__['_%s_typed' % self.attr_name] = value
@overload
def __get__(
self,
instance: None,
owner: Type[object],
) -> Self:
...
@overload
def __get__(
self,
instance: object,
owner: Type[object],
) -> _TypedPropertyGetT:
...
def __get__(
self,
instance: object,
owner: Type[object],
) -> Union[Self, _TypedPropertyGetT]:
"""Return the value of the property.
Args:
instance (object):
The instance owning this property.
owner (type):
The instance's class.
Returns:
object:
The property value.
"""
if instance is None:
return self
return cast(
_TypedPropertyGetT,
instance.__dict__.get('_%s_typed' % self.attr_name, self.default))
def get_descriptor_attr_name(descriptor, cls):
"""Return the name of a property/descriptor instance on a class.
This will go through the class and all parent classes, looking for the
property, and returning its attribute name. This is primarily intended
to help with providing better error messages.
Deprecated:
3.3:
This will be removed in Djblets 5.0. Callers should define
a ``__set_name__()`` method on the descriptor instead.
Args:
descriptor (object):
The instance of the property/descriptor. For a proper value to
be returned, this must exist on ``cls``.
cls (type):
The class owning the property.
Returns:
str:
The name of the property/descriptor.
"""
RemovedInDjblets50Warning.warn(
'djblets.util.properties.get_descriptor_attr_name() is deprecated. '
'Please define a __set_name__() on your descriptor instead. This '
'will be removed in Djblets 5.0.')
for attr_name, attr_value in cls.__dict__.items():
if attr_value is descriptor:
return attr_name
for parent_cls in cls.__mro__:
attr_name = get_descriptor_attr_name(descriptor, parent_cls)
if attr_name is not None:
return attr_name
return None