|
1 # SPDX-License-Identifier: MIT |
|
2 |
|
3 """ |
|
4 Commonly used hooks for on_setattr. |
|
5 """ |
|
6 |
|
7 |
|
8 from . import _config |
|
9 from .exceptions import FrozenAttributeError |
|
10 |
|
11 |
|
12 def pipe(*setters): |
|
13 """ |
|
14 Run all *setters* and return the return value of the last one. |
|
15 |
|
16 .. versionadded:: 20.1.0 |
|
17 """ |
|
18 |
|
19 def wrapped_pipe(instance, attrib, new_value): |
|
20 rv = new_value |
|
21 |
|
22 for setter in setters: |
|
23 rv = setter(instance, attrib, rv) |
|
24 |
|
25 return rv |
|
26 |
|
27 return wrapped_pipe |
|
28 |
|
29 |
|
30 def frozen(_, __, ___): |
|
31 """ |
|
32 Prevent an attribute to be modified. |
|
33 |
|
34 .. versionadded:: 20.1.0 |
|
35 """ |
|
36 raise FrozenAttributeError() |
|
37 |
|
38 |
|
39 def validate(instance, attrib, new_value): |
|
40 """ |
|
41 Run *attrib*'s validator on *new_value* if it has one. |
|
42 |
|
43 .. versionadded:: 20.1.0 |
|
44 """ |
|
45 if _config._run_validators is False: |
|
46 return new_value |
|
47 |
|
48 v = attrib.validator |
|
49 if not v: |
|
50 return new_value |
|
51 |
|
52 v(instance, attrib, new_value) |
|
53 |
|
54 return new_value |
|
55 |
|
56 |
|
57 def convert(instance, attrib, new_value): |
|
58 """ |
|
59 Run *attrib*'s converter -- if it has one -- on *new_value* and return the |
|
60 result. |
|
61 |
|
62 .. versionadded:: 20.1.0 |
|
63 """ |
|
64 c = attrib.converter |
|
65 if c: |
|
66 return c(new_value) |
|
67 |
|
68 return new_value |
|
69 |
|
70 |
|
71 # Sentinel for disabling class-wide *on_setattr* hooks for certain attributes. |
|
72 # autodata stopped working, so the docstring is inlined in the API docs. |
|
73 NO_OP = object() |