Debian Codegraph @

docs/source/traits_user_manual/custom.rst

raw
1 .. index:: custom traits
2
3 .. _custom-traits:
4
5 =============
6 Custom Traits
7 =============
8
9 The predefined traits such as those described in :ref:`predefined-traits` are
10 handy shortcuts for commonly used types. However, the Traits package also
11 provides facilities for defining complex or customized traits:
12
13 * Subclassing of traits
14 * The Trait() factory function
15 * Predefined or custom trait handlers
16
17 .. index:: subclassing traits, TraitType class
18
19 .. _trait-subclassing:
20
21 Trait Subclassing
22 -----------------
23
24 Starting with Traits version 3.0, most predefined traits are defined as
25 subclasses of traits.trait_handlers.TraitType. As a result, you can
26 subclass one of these traits, or TraitType, to derive new traits. Refer to the
27 *Traits API Reference* to see whether a particular predefined trait derives from
28 TraitType.
29
30 .. index::
31 pair: subclassing traits; examples
32
33 Here's an example of subclassing a predefined trait class::
34
35 # trait_subclass.py -- Example of subclassing a trait class
36 from traits.api import BaseInt
37
38 class OddInt ( BaseInt ):
39
40 # Define the default value
41 default_value = 1
42
43 # Describe the trait type
44 info_text = 'an odd integer'
45
46 def validate ( self, object, name, value ):
47 value = super().validate(object, name, value)
48 if (value % 2) == 1:
49 return value
50
51 self.error( object, name, value )
52
53 The OddInt class defines a trait that must be an odd integer. It derives from
54 BaseInt, rather than Int, as you might initially expect. BaseInt and Int are
55 exactly the same, except that Int has a **fast_validate attribute**, which
56 causes it to quickly check types at the C level, not go through the expense of
57 executing the general validate() method. [6]_
58
59 As a subclass of BaseInt, OddInt can reuse and change any part of the BaseInt
60 class behavior that it needs to. In this case, it reuses the BaseInt class's
61 validate() method, via the call to super() in the OddInt validate() method.
62 Further, OddInt is related to BaseInt, which can be useful as documentation, and
63 in programming.
64
65 You can use the subclassing strategy to define either a trait type or a trait
66 property, depending on the specific methods and class constants that you define.
67 A trait type uses a validate() method, while a trait property uses get() and
68 set() methods.
69
70 The :class:`~.TraitType` initializer provides an optional argument
71 ``default_value`` to support easy setting of the default value of the trait
72 type. The default value for that argument is :data:`~.NoDefaultSpecified`: we
73 don't follow the common Python idiom of using ``None`` to represent no default
74 here, since for many trait types ``None`` may be a valid default value. When
75 subclassing :class:`~.TraitType` and overriding or extending its ``__init__``
76 method, it's recommended to re-use the singleton :data:`~.NoDefaultSpecified`
77 if you need a way to indicate that no default value was specified.
78
79
80 .. index: trait type; defining
81
82 .. _defining-a-trait-type:
83
84 Defining a Trait Type
85 `````````````````````
86
87 The members that are specific to a trait type subclass are:
88
89 .. index:: default_value attribute, get_default_value()
90
91 * validate() method
92 * post_setattr() method
93 * **default_value** attribute or get_default_value() method
94
95 Of these, only the validate() method must be overridden in trait type
96 subclasses.
97
98 A trait type uses a validate() method to determine the validity of values
99 assigned to the trait. Optionally, it can define a post_setattr() method, which
100 performs additional processing after a value has been validated and assigned.
101
102 The signatures of these methods are:
103
104 .. method:: validate( object, name, value )
105 .. method:: post_setattr( object, name, value )
106
107 The parameters of these methods are:
108
109 .. index:: object parameter; validate(), name parameter; validate()
110 .. index:: value parameter; validate()
111
112 * *object*: The object whose trait attribute whose value is being assigned.
113 * *name*: The name of the trait attribute whose value is being assigned.
114 * *value*: The value being assigned.
115
116 The validate() method returns either the original value or any suitably coerced
117 or adapted value that is legal for the trait. If the value is not legal, and
118 cannot be coerced or adapted to be legal, the method must either raise a
119 TraitError, or calls the error() method to raise a TraitError on its behalf.
120
121 The subclass can define a default value either as a constant or as a computed
122 value. To use a constant, set the class-level **default_value attribute**. To
123 compute the default value, override the TraitType class's get_default_value()
124 method.
125
126 .. index:: trait property; defining
127
128 .. _defining-a-trait-property:
129
130 Defining a Trait Property
131 `````````````````````````
132
133 A trait property uses get() and set() methods to interact with the value of the
134 trait. If a TraitType subclass contains a get() method or a set() method, any
135 definition it might have for validate() is ignored.
136
137 The signatures of these methods are:
138
139 .. method:: get( object, name)
140 .. method:: set( object, name, value)
141
142 In these signatures, the parameters are:
143
144 * *object*: The object that the property applies to.
145 * *name*: The name of the trait property attribute on the object.
146 * *value*: The value being assigned to the property.
147
148 If only a get() method is defined, the property behaves as read-only. If only a
149 set() method is defined, the property behaves as write-only.
150
151 The get() method returns the value of the *name* property for the specified
152 object. The set() method does not return a value, but will raise a TraitError if
153 the specified *value* is not valid, and cannot be coerced or adapted to a valid
154 value.
155
156 In order for the property to trigger notifications you must call either:
157
158 * object.trait_property_changed(name, old, value) to not cache the value.
159 * self.set_value(object, name, value) to cache the value.
160
161 Likewise if the property will not be read only the get method must use
162 self.get_value(object, name) in order to behave correctly.
163
164 The following example demonstrates the use of a property trait to set temperature::
165
166 class TempFloat(BaseFloat):
167 default_value = 20.0
168 info_text = 'A calculated temperature float in Celsius'
169
170 def set(self, obj, name, value):
171 celsius = (value - 32) * (5/9)
172 setattr(self, name, celsius)
173 self.set_value(obj, name, celsius)
174
175 def get(self, obj, name):
176 val = self.get_value(obj, name)
177 if val is None:
178 val = self.default_value
179 return val
180
181 .. index:: TraitType class; members
182
183 .. _other-traittype-members:
184
185 Other TraitType Members
186 ```````````````````````
187
188 The following members can be specified for either a trait type or a trait
189 property:
190
191 .. index:: info_text attribute, info(), init(), create_editor()
192
193 * **info_text** attribute or info() method
194 * init() method
195 * create_editor() method
196
197 A trait must have an information string that describes the values accepted by
198 the trait type (for example 'an odd integer'). Similarly to the default value,
199 the subclass's information string can be either a constant string or a computed
200 string. To use a constant, set the class-level info_text attribute. To compute
201 the info string, override the TraitType class's info() method, which takes no
202 parameters.
203
204 If there is type-specific initialization that must be performed when the trait
205 type is created, you can override the init() method. This method is
206 automatically called from the __init__() method of the TraitType class.
207
208 If you want to specify a default TraitsUI editor for the new trait type, you
209 can override the create_editor() method. This method has no parameters, and
210 returns the default trait editor to use for any instances of the type.
211
212 For complete details on the members that can be overridden, refer to the *Traits
213 API Reference* sections on the TraitType and BaseTraitHandler classes.
214
215 .. index:: Trait()
216
217 .. _the-trait-factory-function:
218
219 The Trait() Factory Function
220 ----------------------------
221
222 .. note::
223
224 The :func:`~.Trait` function is not recommended for use in new code, and may
225 eventually be deprecated and removed. Consider using :class:`~.Union`
226 instead.
227
228 The Trait() function is a generic factory for trait definitions. It has many
229 forms, many of which are redundant with the predefined shortcut traits. For
230 example, the simplest form Trait(default_value), is equivalent to the functions
231 for simple types described in :ref:`predefined-traits-for-simple-types`. For the
232 full variety of forms of the Trait() function, refer to the *Traits API
233 Reference*.
234
235 The most general form of the Trait() function is:
236
237 .. currentmodule:: traits.traits
238 .. function:: Trait(default_value, {type | constant_value | dictionary | class | function | trait_handler | trait }+ )
239 :noindex:
240
241 .. index:: compound traits
242
243 The notation ``{ | | }+`` means a list of one or more of any of the items listed
244 between the braces. Thus, this form of the function consists of a default value,
245 followed by one or more of several possible items. A trait defined with multiple
246 items is called a compound trait. When more than one item is specified, a trait
247 value is considered valid if it meets the criteria of at least one of the items
248 in the list.
249
250 .. index::
251 pair: Trait() function; examples
252
253 The following is an example of a compound trait with multiple criteria::
254
255 # compound.py -- Example of multiple criteria in a trait definition
256 from traits.api import HasTraits, Trait, Range
257
258 class Die ( HasTraits ):
259
260 # Define a compound trait definition:
261 value = Trait( 1, Range( 1, 6 ),
262 'one', 'two', 'three', 'four', 'five', 'six' )
263
264 The Die class has a **value trait**, which has a default value of 1, and can have
265 any of the following values:
266
267 * An integer in the range of 1 to 6
268 * One of the following strings: 'one', 'two', 'three', 'four', 'five', 'six'
269
270 .. index:: Trait(); parameters
271
272 .. _trait-parameters:
273
274 Trait () Parameters
275 ```````````````````
276
277 The items listed as possible arguments to the Trait() function merit some
278 further explanation.
279
280 .. index:: type; parameter to Trait(), constant_value parameter to Trait()
281 .. index:: dictionary parameter to Trait(), class parameter to Trait()
282 .. index:: function parameter to Trait(), trait handler; parameter to Trait()
283 .. index:: trait; parameter to Trait()
284
285 * *type*: See :ref:`type`.
286 * *constant_value*: See :ref:`constant-value`.
287 * *dictionary*: See :ref:`mapped-traits`.
288 * *class*: Specifies that the trait value must be an instance of the specified
289 class or one of its subclasses.
290 * *function*: A "validator" function that determines whether a value being
291 assigned to the attribute is a legal value. Traits version 3.0 provides a
292 more flexible approach, which is to subclass an existing trait (or TraitType)
293 and override the validate() method.
294 * *trait_handler*: See :ref:`trait-handlers`.
295 * *trait*: Another trait object can be passed as a parameter; any value that is
296 valid for the specified trait is also valid for the trait referencing it.
297
298 .. index:: type; parameter to Trait()
299
300 .. _type:
301
302 Type
303 ::::
304
305 A *type* parameter to the Trait() function can be any of the following standard
306 Python types:
307
308 * str or StringType
309 * int or IntType
310 * float or FloatType
311 * complex or ComplexType
312 * bool or BooleanType
313 * list or ListType
314 * tuple or TupleType
315 * dict or DictType
316 * FunctionType
317 * MethodType
318 * type
319 * NoneType
320
321 Specifying one of these types means that the trait value must be of the
322 corresponding Python type.
323
324 .. index:: constant_value parameter to Trait()
325
326 .. _constant-value:
327
328 Constant Value
329 ::::::::::::::
330
331 A *constant_value* parameter to the Trait() function can be any constant
332 belonging to one of the following standard Python types:
333
334 * NoneType
335 * int
336 * float
337 * complex
338 * bool
339 * str
340
341 Specifying a constant means that the trait can have the constant as a valid
342 value. Passing a list of constants to the Trait() function is equivalent to
343 using the Enum predefined trait.
344
345 .. index:: mapped traits
346
347 .. _mapped-traits:
348
349 Mapped Traits
350 `````````````
351
352 If the Trait() function is called with parameters that include one or more
353 dictionaries, then the resulting trait is called a "mapped" trait. In practice,
354 this means that the resulting object actually contains two attributes:
355
356 .. index:: shadow values
357
358 * An attribute whose value is a key in the dictionary used to define the trait.
359 * An attribute containing its corresponding value (i.e., the mapped or
360 "shadow" value). The name of the shadow attribute is simply the base
361 attribute name with an underscore appended.
362
363 Mapped traits can be used to allow a variety of user-friendly input values to be
364 mapped to a set of internal, program-friendly values.
365
366 .. index:: mapped traits; examples
367
368 The following examples illustrates mapped traits that map color names to tuples
369 representing red, green, blue, and transparency values::
370
371 # mapped.py --- Example of a mapped trait
372 from traits.api import HasTraits, Trait
373
374 standard_color = Trait ('black',
375 {'black': (0.0, 0.0, 0.0, 1.0),
376 'blue': (0.0, 0.0, 1.0, 1.0),
377 'cyan': (0.0, 1.0, 1.0, 1.0),
378 'green': (0.0, 1.0, 0.0, 1.0),
379 'magenta': (1.0, 0.0, 1.0, 1.0),
380 'orange': (0.8, 0.196, 0.196, 1.0),
381 'purple': (0.69, 0.0, 1.0, 1.0),
382 'red': (1.0, 0.0, 0.0, 1.0),
383 'violet': (0.31, 0.184, 0.31, 1.0),
384 'yellow': (1.0, 1.0, 0.0, 1.0),
385 'white': (1.0, 1.0, 1.0, 1.0),
386 'transparent': (1.0, 1.0, 1.0, 0.0) } )
387
388 red_color = Trait ('red', standard_color)
389
390 class GraphicShape (HasTraits):
391 line_color = standard_color
392 fill_color = red_color
393
394 The GraphicShape class has two attributes: **line_color** and **fill_color**.
395 These attributes are defined in terms of the **standard_color** trait, which
396 uses a dictionary. The **standard_color** trait is a mapped trait, which means
397 that each GraphicShape instance has two shadow attributes: **line_color_**
398 and **fill_color_**. Any time a new value is assigned to either **line_color**
399 or **fill_color**, the corresponding shadow attribute is updated with the
400 value in the dictionary corresponding to the value assigned. For example::
401
402 >>> import mapped
403 >>> my_shape1 = mapped.GraphicShape()
404 >>> print(my_shape1.line_color, my_shape1.fill_color)
405 black red
406 >>> print(my_shape1.line_color_, my_shape1.fill_color_)
407 (0.0, 0.0, 0.0, 1.0) (1.0, 0.0, 0.0, 1.0)
408 >>> my_shape2 = mapped.GraphicShape()
409 >>> my_shape2.line_color = 'blue'
410 >>> my_shape2.fill_color = 'green'
411 >>> print(my_shape2.line_color, my_shape2.fill_color)
412 blue green
413 >>> print(my_shape2.line_color_, my_shape2.fill_color_)
414 (0.0, 0.0, 1.0, 1.0) (0.0, 1.0, 0.0, 1.0)
415
416 This example shows how a mapped trait can be used to create a user-friendly
417 attribute (such as **line_color**) and a corresponding program-friendly shadow
418 attribute (such as **line_color_**). The shadow attribute is program-friendly
419 because it is usually in a form that can be directly used by program logic.
420
421 There are a few other points to keep in mind when creating a mapped trait:
422
423 * If not all values passed to the Trait() function are dictionaries, the
424 non-dictionary values are copied directly to the shadow attribute (i.e.,
425 the mapping used is the identity mapping).
426 * Assigning directly to a shadow attribute (the attribute with the trailing
427 underscore in the name) is not allowed, and raises a TraitError.
428
429 The concept of a mapped trait extends beyond traits defined via a dictionary.
430 Any trait that has a shadow value is a mapped trait. For example, for the
431 Expression trait, the assigned value must be a valid Python expression, and the
432 shadow value is the compiled form of the expression.
433
434 .. index:: trait handler; classes
435
436 .. _trait-handlers:
437
438 Trait Handlers
439 --------------
440
441 In some cases, you may want to define a customized trait that is unrelated to
442 any predefined trait behavior, or that is related to a predefined trait that
443 happens to not be derived from TraitType. The option for such cases is to use a
444 trait handler, either a predefined one or a custom one that you write.
445
446 .. index:: TraitHandler class
447
448 A trait handler is an instance of the
449 traits.trait_handlers.TraitHandler class, or of a subclass, whose
450 task is to verify the correctness of values assigned to object traits. When a
451 value is assigned to an object trait that has a trait handler, the trait
452 handler's validate() method checks the value, and assigns that value or a
453 computed value, or raises a TraitError if the assigned value is not valid. Both
454 TraitHandler and TraitType derive from BaseTraitHandler; TraitHandler has a more
455 limited interface.
456
457 The Traits package provides a number of predefined TraitHandler subclasses. A few
458 of the predefined trait handler classes are described in the following sections.
459 These sections also demonstrate how to define a trait using a trait handler and
460 the Trait() factory function. For a complete list and descriptions of predefined
461 TraitHandler subclasses, refer to the *Traits API Reference*, in the section on
462 the traits.trait_handlers module.
463
464 .. index:: TraitPrefixList class
465
466 .. _traitprefixlist:
467
468 TraitPrefixList
469 ```````````````
470
471 .. deprecated:: 6.1
472 :class:`~.TraitPrefixList` is scheduled for removal
473 in Traits 7.0. Use the :class:`~.PrefixList` trait type instead.
474
475 The TraitPrefixList handler accepts not only a specified set of strings as
476 values, but also any unique prefix substring of those values. The value assigned
477 to the trait attribute is the full string that the substring matches.
478
479 .. index::
480 pair: TraitPrefixList class; examples
481
482 For example::
483
484 >>> from traits.api import HasTraits, Trait
485 >>> from traits.api import TraitPrefixList
486 >>> class Alien(HasTraits):
487 ... heads = Trait('one', TraitPrefixList(['one','two','three']))
488 ...
489 >>> alf = Alien()
490 >>> alf.heads = 'o'
491 >>> print(alf.heads)
492 one
493 >>> alf.heads = 'tw'
494 >>> print(alf.heads)
495 two
496 >>> alf.heads = 't' # Error, not a unique prefix
497 Traceback (most recent call last):
498 File "<stdin>", line 1, in <module>
499 File "c:\svn\ets3\traits_3.0.3\enthought\traits\trait_handlers.py", line 1802,
500 in validate self.error( object, name, value )
501 File "c:\svn\ets3\traits_3.0.3\enthought\traits\trait_handlers.py", line 175,
502 in error value )
503 traits.trait_errors.TraitError: The 'heads' trait of an Alien instance
504 must be 'one' or 'two' or 'three' (or any unique prefix), but a value of 't'
505 <type 'str'> was specified.
506
507 .. index:: TraitPrefixMap class
508
509 .. _traitprefixmap:
510
511 TraitPrefixMap
512 ``````````````
513
514 .. deprecated:: 6.1
515 :class:`~.TraitPrefixMap` is scheduled for removal
516 in Traits 7.0. Use the :class:`~.PrefixMap` trait type instead.
517
518 The TraitPrefixMap handler combines the TraitPrefixList with mapped traits. Its
519 constructor takes a parameter that is a dictionary whose keys are strings. A
520 string is a valid value if it is a unique prefix for a key in the dictionary.
521 The value assigned is the dictionary value corresponding to the matched key.
522
523 .. index::
524 pair: TraitPrefixMap class; examples
525
526 The following example uses TraitPrefixMap to define a Boolean trait that accepts
527 any prefix of 'true', 'yes', 'false', or 'no', and maps them to 1 or 0.
528 ::
529
530 # traitprefixmap.py --- Example of using the TraitPrefixMap handler
531 from traits.api import Trait, TraitPrefixMap
532
533 boolean_map = Trait('true', TraitPrefixMap( {
534 'true': 1,
535 'yes': 1,
536 'false': 0,
537 'no': 0 } ) )
538
539 .. index:: handler classes; custom
540
541 .. _custom-trait-handlers:
542
543 Custom Trait Handlers
544 ---------------------
545
546 If you need a trait that cannot be defined using a predefined trait handler
547 class, you can create your own subclass of TraitHandler. The constructor
548 (i.e., __init__() method) for your TraitHandler subclass can accept whatever
549 additional information, if any, is needed to completely specify the trait. The
550 constructor does not need to call the TraitHandler base class's constructor.
551
552 The only method that a custom trait handler must implement is validate(). Refer
553 to the *Traits API Reference* for details about this function.
554
555 .. index::
556 pair: custom trait handler; examples
557
558 .. _example-custom-trait-handler:
559
560 Example Custom Trait Handler
561 ````````````````````````````
562
563 The following example defines the OddInt trait (also implemented as a trait type
564 in :ref:`defining-a-trait-type`) using a TraitHandler subclass.
565 ::
566
567 # custom_traithandler.py --- Example of a custom TraitHandler
568 import types
569 from traits.api import TraitHandler
570
571 class TraitOddInteger(TraitHandler):
572 def validate(self, object, name, value):
573 if ((type(value) is types.IntType) and
574 (value > 0) and ((value % 2) == 1)):
575 return value
576 self.error(object, name, value)
577
578 def info(self):
579 return '**a positive odd integer**'
580
581 An application could use this new trait handler to define traits such as the
582 following::
583
584 # use_custom_th.py --- Example of using a custom TraitHandler
585 from traits.api import HasTraits, Range, Trait
586 from custom_traithandler import TraitOddInteger
587
588 class AnOddClass(HasTraits):
589 oddball = Trait(1, TraitOddInteger())
590 very_odd = Trait(-1, TraitOddInteger(), Range(-10, -1))
591
592 The following example demonstrates why the info() method returns a phrase rather
593 than a complete sentence::
594
595 >>> from use_custom_th import AnOddClass
596 >>> odd_stuff = AnOddClass()
597 >>> odd_stuff.very_odd = 0
598 Traceback (most recent call last):
599 File "test.py", line 25, in ?
600 odd_stuff.very_odd = 0
601 File "C:\wrk\src\lib\enthought\traits\traits.py", line 1119, in validate
602 raise TraitError(excp)
603 traits.traits.TraitError: The 'very_odd' trait of an AnOddClass instance
604 must be **a positive odd integer** or -10 <= an integer <= -1, but a value
605 of 0 <type 'int'> was specified.
606
607 Note the emphasized result returned by the info() method, which is embedded in
608 the exception generated by the invalid assignment.
609
610 .. rubric:: Footnotes
611
612 .. [6] All of the basic predefined traits (such as Float and Str) have a
613 BaseType version that does not have the **fast_validate** attribute.