Debian Codegraph @

docs/source/traits_user_manual/deferring.rst

raw
1 .. index:: deferral
2
3 .. _deferring-traits:
4
5 Deferring Trait Definitions
6 ===========================
7
8 One of the advanced capabilities of the Traits package is its support for trait
9 attributes to defer their definition and value to another object than the one
10 the attribute is defined on. This has many applications, especially in cases
11 where objects are logically contained within other objects and may wish to
12 inherit or derive some attributes from the object they are contained in or
13 associated with. Deferring leverages the common "has-a" relationship between
14 objects, rather than the "is-a" relationship that class inheritance provides.
15
16 .. index:: delegation, prototyping
17
18 There are two ways that a trait attribute can defer to another object's
19 attribute: *delegation* and *prototyping*. In delegation, the deferring
20 attribute is a complete reflection of the delegate attribute. Both the value and
21 validation of the delegate attribute are used for the deferring attribute;
22 changes to either one are reflected in both. In prototyping, the deferring
23 attribute gets its value and validation from the prototype attribute, *until the
24 deferring attribute is explicitly changed*. At that point, while the deferring
25 attribute still uses the prototype's validation, the link between the values is
26 broken, and the two attributes can change independently. This is essentially a
27 "copy on write" scheme.
28
29 The concepts of delegation and prototyping are implemented in the Traits package
30 by two classes derived from TraitType: DelegatesTo and PrototypedFrom. [5]_
31
32 .. _delegatesto:
33
34 DelegatesTo
35 -----------
36
37 .. class:: DelegatesTo(delegate[, prefix='', listenable=True, **metadata])
38
39 .. index:: delegate parameter to DelegatesTo initializer
40
41 The *delegate* parameter is a string that specifies the name of an attribute
42 on the same object, which refers to the object whose attribute is deferred to;
43 it is usually an Instance trait. The value of the delegating attribute changes
44 whenever:
45
46 * The value of the appropriate attribute on the delegate object changes.
47 * The object referenced by the trait named in the *delegate* parameter changes.
48 * The delegating attribute is explicitly changed.
49
50 Changes to the delegating attribute are propagated to the delegate object's
51 attribute.
52
53 The *prefix* and *listenable* parameters to the initializer function specify
54 additional information about how to do the delegation.
55
56 .. index::
57 pair: delegation; examples
58
59 If *prefix* is the empty string or omitted, the delegation is to an attribute
60 of the delegate object with the same name as the trait defined by the
61 DelegatesTo object. Consider the following example::
62
63 # delegate.py --- Example of trait delegation
64 from traits.api \
65 import DelegatesTo, HasTraits, Instance, Str
66
67 class Parent(HasTraits):
68 first_name = Str
69 last_name = Str
70
71 class Child(HasTraits):
72 first_name = Str
73 last_name = DelegatesTo('father')
74 father = Instance(Parent)
75 mother = Instance(Parent)
76
77 """
78 >>> tony = Parent(first_name='Anthony', last_name='Jones')
79 >>> alice = Parent(first_name='Alice', last_name='Smith')
80 >>> sally = Child( first_name='Sally', father=tony, mother=alice)
81 >>> print(sally.last_name)
82 Jones
83 >>> sally.last_name = 'Cooper' # Updates delegatee
84 >>> print(tony.last_name)
85 Cooper
86 >>> sally.last_name = sally.mother # ERR: string expected
87 Traceback (most recent call last):
88 File "<stdin>", line 1, in ?
89 File "c:\src\trunk\enthought\traits\trait_handlers.py", line
90 163, in error
91 raise TraitError( object, name, self.info(), value )
92 traits.trait_errors.TraitError: The 'last_name' trait of a
93 Parent instance must be a string, but a value of <__main__.Parent object at
94 0x014D6D80> <class '__main__.Parent'> was specified.
95 """
96
97 A Child object delegates its **last_name** attribute value to its **father**
98 object's **last_name** attribute. Because the *prefix* parameter was not
99 specified in the DelegatesTo initializer, the attribute name on the delegatee is
100 the same as the original attribute name. Thus, the **last_name** of a Child is
101 the same as the **last_name** of its **father**. When either the **last_name**
102 of the Child or the **last_name** of the father is changed, both attributes
103 reflect the new value.
104
105 .. _prototypedfrom:
106
107 PrototypedFrom
108 --------------
109 .. class:: PrototypedFrom(prototype[, prefix='', listenable=True, **metadata])
110
111 .. index:: prototype parameter to PrototypesFrom
112
113 The *prototype* parameter is a string that specifies the name of an attribute on
114 the same object, which refers to the object whose attribute is prototyped; it is
115 usually an Instance trait. The prototyped attribute behaves similarly to a
116 delegated attribute, until it is explicitly changed; from that point forward,
117 the prototyped attribute changes independently from its prototype.
118
119 The *prefix* and *listenable* parameters to the initializer function specify
120 additional information about how to do the prototyping.
121
122 .. _keyword-parameters:
123
124 Keyword Parameters
125 ------------------
126
127 The *prefix* and *listenable* parameters of the DelegatesTo and PrototypedFrom
128 initializer functions behave similarly for both classes.
129
130 .. index:: prefix parameter to initializer methods
131
132 .. _prefix-keyword:
133
134 Prefix Keyword
135 ``````````````
136
137 When the *prefix* parameter is a non-empty string, the rule for performing trait
138 attribute look-up in the deferred-to object is modified, with the modification
139 depending on the format of the prefix string:
140
141 * If *prefix* is a valid Python attribute name, then the original attribute
142 name is replaced by prefix when looking up the deferred-to attribute.
143 * If *prefix* ends with an asterisk ('*'), and is longer than one character,
144 then *prefix*, minus the trailing asterisk, is added to the front of the
145 original attribute name when looking up the object attribute.
146 * If *prefix* is equal to a single asterisk ('*'), the value of the object
147 class's **__prefix__** attribute is added to the front of the original
148 attribute name when looking up the object attribute.
149
150 .. index::
151 single: examples; prototype prefix
152 pair: examples; prototyping
153
154 Each of these three possibilities is illustrated in the following example, using
155 PrototypedFrom::
156
157 # prototype_prefix.py --- Examples of PrototypedFrom()
158 # prefix parameter
159 from traits.api import \
160 PrototypedFrom, Float, HasTraits, Instance, Str
161
162 class Parent (HasTraits):
163 first_name = Str
164 family_name = ''
165 favorite_first_name = Str
166 child_allowance = Float(1.00)
167 class Child (HasTraits):
168 __prefix__ = 'child_'
169 first_name = PrototypedFrom('mother', 'favorite_*')
170 last_name = PrototypedFrom('father', 'family_name')
171 allowance = PrototypedFrom('father', '*')
172 father = Instance(Parent)
173 mother = Instance(Parent)
174
175 """
176 >>> fred = Parent( first_name = 'Fred', family_name = 'Lopez', \
177 ... favorite_first_name = 'Diego', child_allowance = 5.0 )
178 >>> maria = Parent(first_name = 'Maria', family_name = 'Gonzalez',\
179 ... favorite_first_name = 'Tomas', child_allowance = 10.0 )
180 >>> nino = Child( father=fred, mother=maria )
181 >>> print('%s %s gets $%.2f for allowance' % (nino.first_name, \ ... nino.last_name, nino.allowance))
182 Tomas Lopez gets $5.00 for allowance
183 """
184
185 In this example, instances of the Child class have three prototyped trait
186 attributes:
187
188 * **first_name**, which prototypes from the **favorite_first_name** attribute
189 of its **mother** object.
190 * **last_name**, which prototyped from the **family_name attribute** of its
191 **father** object.
192 * **allowance**, which prototypes from the **child_allowance** attribute of its
193 **father** object.
194
195 .. index:: listenable parameter to initializer methods
196
197 .. _listenable-keyword:
198
199 Listenable Keyword
200 ``````````````````
201
202 By default, you can attach listeners to deferred trait attributes, just as you
203 can attach listeners to most other trait attributes, as described in the
204 following section. However, implementing the notifications correctly requires
205 hooking up complicated listeners under the covers. Hooking up these listeners
206 can be rather more expensive than hooking up other listeners. Since a common use
207 case of deferring is to have a large number of deferred attributes for static
208 object hierarchies, this feature can be turned off by setting
209 ``listenable=False`` in order to speed up instantiation.
210
211 .. index::
212 single: deferral; notification with
213 pair: examples; deferral
214
215 .. _notification-with-deferring:
216
217 Notification with Deferring
218 ---------------------------
219
220 While two trait attributes are linked by a deferring relationship (either
221 delegation, or prototyping before the link is broken), notifications for changes
222 to those attributes are linked as well. When the value of a deferred-to
223 attribute changes, notification is sent to any handlers on the deferring object,
224 as well as on the deferred-to object. This behavior is new in Traits version
225 3.0. In previous versions, only handlers for the deferred-to object (the object
226 directly changed) were notified. This behavior is shown in the following
227 example::
228
229 # deferring_notification.py -- Example of notification with deferring
230 from traits.api \
231 import HasTraits, Instance, PrototypedFrom, Str
232
233 class Parent ( HasTraits ):
234
235 first_name = Str
236 last_name = Str
237
238 def _last_name_changed(self, new):
239 print("Parent's last name changed to %s." % new)
240
241 class Child ( HasTraits ):
242
243 father = Instance( Parent )
244 first_name = Str
245 last_name = PrototypedFrom( 'father' )
246
247 def _last_name_changed(self, new):
248 print("Child's last name changed to %s." % new)
249
250 """
251 >>> dad = Parent( first_name='William', last_name='Chase' )
252 Parent's last name changed to Chase.
253 >>> son = Child( first_name='John', father=dad )
254 Child's last name changed to Chase.
255 >>> dad.last_name='Jones'
256 Parent's last name changed to Jones.
257 Child's last name changed to Jones.
258 >>> son.last_name='Thomas'
259 Child's last name changed to Thomas.
260 >>> dad.last_name='Riley'
261 Parent's last name changed to Riley.
262 >>> del son.last_name
263 Child's last name changed to Riley.
264 >>> dad.last_name='Simmons'
265 Parent's last name changed to Simmons.
266 Child's last name changed to Simmons.
267 """
268
269 Initially, changing the last name of the father triggers notification on both
270 the father and the son. Explicitly setting the son's last name breaks the
271 deferring link to the father; therefore changing the father's last name does not
272 notify the son. When the son reverts to using the father's last name (by
273 deleting the explicit value), changes to the father's last name again affect and
274 notif
275
276 .. rubric:: Footnotes
277
278 .. [5] Both of these class es inherit from the Delegate class. Explicit use of
279 Delegate is deprecated, as its name and default behavior (prototyping) are
280 incongruous.
281