1
1
"""Descriptor support for NIPY
2
2
3
- Utilities to support special Python descriptors [1,2], in particular the use of
4
- a useful pattern for properties we call 'one time properties'. These are
5
- object attributes which are declared as properties, but become regular
6
- attributes once they've been read the first time. They can thus be evaluated
3
+ Utilities to support special Python descriptors [1,2], in particular
4
+ :func:`~functools.cached_property`, which has been available in the Python
5
+ standard library since Python 3.8. We currently maintain aliases from
6
+ earlier names for this descriptor, specifically `OneTimeProperty` and `auto_attr`.
7
+
8
+ :func:`~functools.cached_property` creates properties that are computed once
9
+ and then stored as regular attributes. They can thus be evaluated
7
10
later in the object's life cycle, but once evaluated they become normal, static
8
11
attributes with no function call overhead on access or any other constraints.
9
12
21
24
22
25
from __future__ import annotations
23
26
24
- import typing as ty
25
-
26
- InstanceT = ty .TypeVar ('InstanceT' )
27
- T = ty .TypeVar ('T' )
27
+ from functools import cached_property
28
28
29
29
from nibabel .deprecated import deprecate_with_version
30
30
34
34
35
35
36
36
class ResetMixin :
37
- """A Mixin class to add a .reset() method to users of OneTimeProperty .
37
+ """A Mixin class to add a .reset() method to users of cached_property .
38
38
39
- By default, auto attributes once computed, become static. If they happen
39
+ By default, cached properties, once computed, become static. If they happen
40
40
to depend on other parts of an object and those parts change, their values
41
41
may now be invalid.
42
42
43
43
This class offers a .reset() method that users can call *explicitly* when
44
44
they know the state of their objects may have changed and they want to
45
45
ensure that *all* their special attributes should be invalidated. Once
46
- reset() is called, all their auto attributes are reset to their
47
- OneTimeProperty descriptors, and their accessor functions will be triggered
48
- again.
46
+ reset() is called, all their cached properties are reset to their
47
+ :func:`~functools.cached_property` descriptors,
48
+ and their accessor functions will be triggered again.
49
49
50
50
.. warning::
51
51
52
- If a class has a set of attributes that are OneTimeProperty , but that
52
+ If a class has a set of attributes that are cached_property , but that
53
53
can be initialized from any one of them, do NOT use this mixin! For
54
54
instance, UniformTimeSeries can be initialized with only sampling_rate
55
55
and t0, sampling_interval and time are auto-computed. But if you were
@@ -68,33 +68,37 @@ class ResetMixin:
68
68
... def __init__(self,x=1.0):
69
69
... self.x = x
70
70
...
71
- ... @auto_attr
71
+ ... @cached_property
72
72
... def y(self):
73
73
... print('*** y computation executed ***')
74
74
... return self.x / 2.0
75
- ...
76
75
77
76
>>> a = A(10)
78
77
79
78
About to access y twice, the second time no computation is done:
79
+
80
80
>>> a.y
81
81
*** y computation executed ***
82
82
5.0
83
83
>>> a.y
84
84
5.0
85
85
86
86
Changing x
87
+
87
88
>>> a.x = 20
88
89
89
90
a.y doesn't change to 10, since it is a static attribute:
91
+
90
92
>>> a.y
91
93
5.0
92
94
93
95
We now reset a, and this will then force all auto attributes to recompute
94
96
the next time we access them:
97
+
95
98
>>> a.reset()
96
99
97
100
About to access y twice again after reset():
101
+
98
102
>>> a.y
99
103
*** y computation executed ***
100
104
10.0
@@ -103,88 +107,18 @@ class ResetMixin:
103
107
"""
104
108
105
109
def reset (self ) -> None :
106
- """Reset all OneTimeProperty attributes that may have fired already."""
110
+ """Reset all cached_property attributes that may have fired already."""
107
111
# To reset them, we simply remove them from the instance dict. At that
108
112
# point, it's as if they had never been computed. On the next access,
109
113
# the accessor function from the parent class will be called, simply
110
114
# because that's how the python descriptor protocol works.
111
115
for mname , mval in self .__class__ .__dict__ .items ():
112
- if mname in self .__dict__ and isinstance (mval , OneTimeProperty ):
116
+ if mname in self .__dict__ and isinstance (mval , cached_property ):
113
117
delattr (self , mname )
114
118
115
119
116
- class OneTimeProperty (ty .Generic [T ]):
117
- """A descriptor to make special properties that become normal attributes.
118
-
119
- This is meant to be used mostly by the auto_attr decorator in this module.
120
- """
121
-
122
- def __init__ (self , func : ty .Callable [[InstanceT ], T ]) -> None :
123
- """Create a OneTimeProperty instance.
124
-
125
- Parameters
126
- ----------
127
- func : method
128
-
129
- The method that will be called the first time to compute a value.
130
- Afterwards, the method's name will be a standard attribute holding
131
- the value of this computation.
132
- """
133
- self .getter = func
134
- self .name = func .__name__
135
- self .__doc__ = func .__doc__
136
-
137
- @ty .overload
138
- def __get__ (
139
- self , obj : None , objtype : type [InstanceT ] | None = None
140
- ) -> ty .Callable [[InstanceT ], T ]: ...
141
-
142
- @ty .overload
143
- def __get__ (self , obj : InstanceT , objtype : type [InstanceT ] | None = None ) -> T : ...
144
-
145
- def __get__ (
146
- self , obj : InstanceT | None , objtype : type [InstanceT ] | None = None
147
- ) -> T | ty .Callable [[InstanceT ], T ]:
148
- """This will be called on attribute access on the class or instance."""
149
- if obj is None :
150
- # Being called on the class, return the original function. This
151
- # way, introspection works on the class.
152
- return self .getter
153
-
154
- # Errors in the following line are errors in setting a OneTimeProperty
155
- val = self .getter (obj )
156
-
157
- obj .__dict__ [self .name ] = val
158
- return val
159
-
160
-
161
- def auto_attr (func : ty .Callable [[InstanceT ], T ]) -> OneTimeProperty [T ]:
162
- """Decorator to create OneTimeProperty attributes.
163
-
164
- Parameters
165
- ----------
166
- func : method
167
- The method that will be called the first time to compute a value.
168
- Afterwards, the method's name will be a standard attribute holding the
169
- value of this computation.
170
-
171
- Examples
172
- --------
173
- >>> class MagicProp:
174
- ... @auto_attr
175
- ... def a(self):
176
- ... return 99
177
- ...
178
- >>> x = MagicProp()
179
- >>> 'a' in x.__dict__
180
- False
181
- >>> x.a
182
- 99
183
- >>> 'a' in x.__dict__
184
- True
185
- """
186
- return OneTimeProperty (func )
187
-
120
+ OneTimeProperty = cached_property
121
+ auto_attr = cached_property
188
122
189
123
# -----------------------------------------------------------------------------
190
124
# Deprecated API
0 commit comments