Debian Codegraph @

docs/source/traits_user_manual/defining.rst

raw
1 .. index:: validation, using traits
2
3 .. _defining-traits-initialization-and-validation:
4
5 ==============================================
6 Defining Traits: Initialization and Validation
7 ==============================================
8
9 Using the Traits package in a Python program involves the following steps:
10
11 .. index:: importing Traits names, traits.api; importing from
12
13 1. Import the names you need from the Traits package traits.api.
14
15 2. Define the traits you want to use.
16
17 .. index:: HasTraits class
18
19 3. Define classes derived from HasTraits (or a subclass of HasTraits), with
20 attributes that use the traits you have defined.
21
22 In practice, steps 2 and 3 are often combined by defining traits in-line
23 in an attribute definition. This strategy is used in many examples in this
24 guide. However, you can also define traits independently, and reuse the trait
25 definitions across multiple classes and attributes (see
26 :ref:`reusing-trait-definitions`).
27
28 In order to use trait attributes in a class, the class must inherit from the
29 HasTraits class in the Traits package (or from a subclass of HasTraits). The
30 following example defines a class called Person that has a single trait
31 attribute **weight**, which is initialized to 150.0 and can only take floating
32 point values.
33
34 .. index::
35 single: examples; minimal
36
37 ::
38
39 # minimal.py --- Minimal example of using traits.
40
41 from traits.api import HasTraits, Float
42
43 class Person(HasTraits):
44 weight = Float(150.0)
45
46 .. index:: attribute definition
47
48 In this example, the attribute named **weight** specifies that the class has a
49 corresponding trait called **weight**. The value associated with the attribute
50 **weight** (i.e., ``Float(150.0)``) specifies a predefined trait provided with
51 the Traits package, which requires that values assigned be of the standard
52 Python type **float**. The value 150.0 specifies the default value of the
53 trait.
54
55 The value associated with each class-level attribute determines the
56 characteristics of the instance attribute identified by the attribute name.
57 For example::
58
59 >>> from minimal import Person
60 >>> # instantiate the class
61 >>> joe = Person()
62 >>> # Show the default value
63 >>> joe.weight
64 150.0
65 >>> # Assign new values
66 >>> joe.weight = 161.9 # OK to assign a float
67 >>> joe.weight = 162 # OK to assign an int
68 >>> joe.weight = 'average' # Error to assign a string
69 Traceback (most recent call last):
70 ...
71 traits.trait_errors.TraitError: The 'weight' trait of a Person instance
72 must be a float, but a value of 'average' <type 'str'> was specified.
73
74 In this example, **joe** is an instance of the Person class defined in the
75 previous example. The **joe** object has an instance attribute **weight**,
76 whose initial value is the default value of the Person.weight trait (150.0),
77 and whose assignment is governed by the Person.weight trait's validation
78 rules. Assigning an integer to **weight** is acceptable because there is no
79 loss of precision (but assigning a float to an Int trait would cause an error).
80
81 The Traits package allows creation of a wide variety of trait types, ranging
82 from very simple to very sophisticated. The following section presents some of
83 the simpler, more commonly used forms.
84
85 .. warning:: Unless otherwise stated as safe to do so, avoid naming
86 attributes with the prefix 'trait' or '_trait'. This avoids overshadowing
87 existing methods on HasTraits.
88
89
90 A note about the Traits package structure
91 -----------------------------------------
92
93 We described above how trait type definitions and the :class:`~.HasTraits`
94 class can be imported from the ``traits.api`` module. For example::
95
96 from traits.api import Float, HasTraits, Int
97
98 In fact, the :class:`HasTraits` class and various trait type classes are
99 defined in other modules nested inside the Traits package structure, but
100 they're re-imported to ``traits.api`` for user convenience. In general,
101 everything you need should be available in either ``traits.api`` or one of the
102 other ``*.api`` modules inside the package structure (for example,
103 ``traits.adaptation.api`` or ``traits.observation.api``). As a matter of best
104 practices, you should import the things you need directly from one of these
105 ``*.api`` modules. If you discover that there's something that you need that's
106 not available from one of these modules, please discuss with the Traits
107 development team (for example, by opening an issue on the `Traits bug
108 tracker`_).
109
110
111 .. index:: predefined traits
112
113 .. _predefined-traits:
114
115 Predefined Traits
116 -----------------
117 The Traits package includes a large number of predefined traits for commonly
118 used Python data types. In the simplest case, you can assign the trait name
119 to an attribute of a class derived from HasTraits; any instances of the class
120 will have that attribute initialized to the built-in default value for the
121 trait. For example::
122
123 account_balance = Float
124
125 This statement defines an attribute whose value must be a floating point
126 number, and whose initial value is 0.0 (the built-in default value for Floats).
127
128 If you want to use an initial value other than the built-in default, you can
129 pass it as an argument to the trait::
130
131 account_balance = Float(10.0)
132
133 Most predefined traits are callable [1]_, and can accept a default value and
134 possibly other arguments; all that are callable can also accept metadata as
135 keyword arguments. (See :ref:`other-predefined-traits` for information on trait
136 signatures, and see :ref:`trait-metadata` for information on metadata
137 arguments.)
138
139 .. index:: simple types
140
141 .. _predefined-traits-for-simple-types:
142
143 Predefined Traits for Simple Types
144 ``````````````````````````````````
145 There are two categories of predefined traits corresponding to Python simple
146 types: those that coerce values, and those that cast values. These categories
147 vary in the way that they handle assigned values that do not match the type
148 explicitly defined for the trait. However, they are similar in terms of the
149 Python types they correspond to, and their built-in default values, as listed
150 in the following table.
151
152 .. index::
153 pair: types; casting
154 pair: types; coercing
155 pair: type; string
156 .. index:: Boolean type, Bool trait, CBool trait, Complex trait, CComplex trait
157 .. index:: Float trait, CFloat trait, Int trait, CInt trait
158 .. index:: integer type, floating point number type, complex number type
159 .. index:: Str trait, CStr trait, Bytes trait, CBytes trait
160
161 .. _predefined-defaults-for-simple-types-table:
162
163 .. rubric:: Predefined defaults for simple types
164
165 ============== ============= ====================== ======================
166 Coercing Trait Casting Trait Python Type Built-in Default Value
167 ============== ============= ====================== ======================
168 Bool CBool Boolean False
169 Complex CComplex Complex number 0+0j
170 Float CFloat Floating point number 0.0
171 Int CInt Integer 0
172 Str CStr String ''
173 Bytes CBytes Bytes b''
174 ============== ============= ====================== ======================
175
176 .. index::
177 pair: types; coercing
178
179 .. _trait-type-coercion:
180
181 Trait Type Coercion
182 :::::::::::::::::::
183 For trait attributes defined using the predefined "coercing"
184 traits, if a value is assigned to a trait attribute that is not of the type
185 defined for the trait, but it can be coerced to the required type, then the
186 coerced value is assigned to the attribute. If the value cannot be coerced to
187 the required type, a TraitError exception is raised. Only widening coercions
188 are allowed, to avoid any possible loss of precision. The following table
189 lists traits that coerce values, and the types that each coerces.
190
191 .. index::
192 pair: types; coercing
193
194 .. _type-coercions-permitted-for-coercing-traits-table:
195
196 .. rubric:: Type coercions permitted for coercing traits
197
198 ============= ===========================================
199 Trait Coercible Types
200 ============= ===========================================
201 Complex Floating point number, integer
202 Float Integer
203 ============= ===========================================
204
205 .. index::
206 pair: types; casting
207
208 .. _trait-type-casting:
209
210 Trait Type Casting
211 ::::::::::::::::::
212 For trait attributes defined using the predefined "casting"
213 traits, if a value is assigned to a trait attribute that is not of the type
214 defined for the trait, but it can be cast to the required type, then the cast
215 value is assigned to the attribute. If the value cannot be cast to the required
216 type, a TraitError exception is raised. Internally, casting is done using the
217 Python built-in functions for type conversion:
218
219 * bool()
220 * complex()
221 * float()
222 * int()
223 * str()
224 * bytes()
225
226 .. index::
227 single: examples; coercing vs. casting
228
229 The following example illustrates the difference between coercing traits and
230 casting traits::
231
232 >>> from traits.api import HasTraits, Float, CFloat
233 >>> class Person ( HasTraits ):
234 ... weight = Float
235 ... cweight = CFloat
236 ...
237 >>> bill = Person()
238 >>> bill.weight = 180 # OK, coerced to 180.0
239 >>> bill.cweight = 180 # OK, cast to float(180)
240 >>> bill.weight = '180' # Error, invalid coercion
241 Traceback (most recent call last):
242 ...
243 traits.trait_errors.TraitError: The 'weight' trait of a Person instance
244 must be a float, but a value of '180' <type 'str'> was specified.
245 >>> bill.cweight = '180' # OK, cast to float('180')
246 >>> print(bill.cweight)
247 180.0
248
249
250 .. _other-predefined-traits:
251
252 Other Predefined Traits
253 ```````````````````````
254 The Traits package provides a number of other predefined traits besides those
255 for simple types, corresponding to other commonly used data types; these
256 predefined traits are listed in the following table. Refer to the
257 *Traits API Reference*, in the section for the module traits.traits,
258 for details. Most can be used either as simple names, which use their built-in
259 default values, or as callables, which can take additional arguments. If the
260 trait cannot be used as a simple name, it is omitted from the Name column of
261 the table.
262
263 .. index:: Any(), Array(), Button(), Callable(), CArray(), Code()
264 .. index:: CSet(), Constant(), Date(), Datetime(), Dict()
265 .. index:: Directory(), Disallow, Either(), Enum()
266 .. index:: Event(), Expression(), false, File()
267 .. index:: Instance(), List(), Method(), Module()
268 .. index:: Password(), Property(), Python()
269 .. index:: PythonValue(), Range(), ReadOnly(), Regex()
270 .. index:: Set() String(), This, Time()
271 .. index:: ToolbarButton(), true, Tuple(), Type()
272 .. index:: undefined, Union(), UUID(), ValidatedTuple(), WeakRef()
273
274 .. _predefined-traits-beyond-simple-types-table:
275
276 .. rubric:: Predefined traits beyond simple types
277
278 +------------------+----------------------------------------------------------+
279 | Name | Callable Signature |
280 +==================+==========================================================+
281 | Any | Any( [*default_value* = None, \*, |
282 | | *factory* = None, *args* = (), *kw* = {}, |
283 | | \*\*\ *metadata*] ) |
284 +------------------+----------------------------------------------------------+
285 | Array | Array( [*dtype* = None, *shape* = None, *value* = None, |
286 | | *typecode* = None, \*\*\ *metadata*] ) |
287 +------------------+----------------------------------------------------------+
288 | ArrayOrNone | ArrayOrNone( [*dtype* = None, *shape* = None, |
289 | | *value* = None, *typecode* = None, \*\*\ *metadata*] ) |
290 +------------------+----------------------------------------------------------+
291 | Button | Button( [*label* = '', *image* = None, *style* = |
292 | | 'button', *orientation* = 'vertical', *width_padding* = |
293 | | 7, *height_padding* = 5, \*\*\ *metadata*] ) |
294 +------------------+----------------------------------------------------------+
295 | Callable | Callable( [*value* = None, \*\*\ *metadata*] ) |
296 +------------------+----------------------------------------------------------+
297 | CArray | CArray( [*dtype* = None, *shape* = None, *value* = None, |
298 | | *typecode* = None, \*\*\ *metadata*] ) |
299 +------------------+----------------------------------------------------------+
300 | Code | Code( [*value* = '', *minlen* = 0, |
301 | | *maxlen* = sys.maxsize, *regex* = '', |
302 | | \*\*\ *metadata*] ) |
303 +------------------+----------------------------------------------------------+
304 | CSet | CSet( [*trait* = None, *value* = None, *items* = True, |
305 | | \*\*\ *metadata*] ) |
306 +------------------+----------------------------------------------------------+
307 | Constant | Constant( *value*\ [, \*\*\ *metadata*] ) |
308 +------------------+----------------------------------------------------------+
309 | Date | Date( *value*\ [, *default_value* = None, |
310 | | *allow_datetime* = None, *allow_none* = None, |
311 | | \*\*\ *metadata*] ) |
312 +------------------+----------------------------------------------------------+
313 | Datetime | Datetime( *value*\ [, *default_value* = None, |
314 | | *allow_none* = None, \*\*\ *metadata*]) |
315 +------------------+----------------------------------------------------------+
316 | Dict | Dict( [*key_trait* = None, *value_trait* = None, |
317 | | *value* = None, *items* = True, \*\*\ *metadata*] ) |
318 +------------------+----------------------------------------------------------+
319 | Directory | Directory( [*value* = '', *auto_set* = False, *entries* =|
320 | | 10, *exists* = False, \*\*\ *metadata*] ) |
321 +------------------+----------------------------------------------------------+
322 | Disallow | n/a |
323 +------------------+----------------------------------------------------------+
324 | Either [2]_ | Either( *val1*\ [, *val2*, ..., *valN*, |
325 | | \*\*\ *metadata*] ) |
326 +------------------+----------------------------------------------------------+
327 | Enum | Enum( *values*\ [, \*\*\ *metadata*] ) |
328 +------------------+----------------------------------------------------------+
329 | Event | Event( [*trait* = None, \*\*\ *metadata*] ) |
330 +------------------+----------------------------------------------------------+
331 | Expression | Expression( [*value* = '0', \*\*\ *metadata*] ) |
332 +------------------+----------------------------------------------------------+
333 | File | File( [*value* = '', *filter* = None, *auto_set* = False,|
334 | | *entries* = 10, *exists* = False, \*\*\ *metadata* ] ) |
335 +------------------+----------------------------------------------------------+
336 | Function [3]_ | Function( [*value* = None, \*\*\ *metadata*] ) |
337 +------------------+----------------------------------------------------------+
338 | generic_trait | n/a |
339 +------------------+----------------------------------------------------------+
340 | HTML | HTML( [*value* = '', *minlen* = 0, |
341 | | *maxlen* = sys.maxsize, *regex* = '', |
342 | | \*\*\ *metadata* ] ) |
343 +------------------+----------------------------------------------------------+
344 | Instance | Instance( [*klass* = None, *factory* = None, *args* = |
345 | | None, *kw* = None, *allow_none* = True, *adapt* = None, |
346 | | *module* = None, \*\*\ *metadata*] ) |
347 +------------------+----------------------------------------------------------+
348 | List | List( [*trait* = None, *value* = None, *minlen* = 0, |
349 | | *maxlen* = sys.maxsize, *items* = True, |
350 | | \*\*\ *metadata*] ) |
351 +------------------+----------------------------------------------------------+
352 | Map | Map( *map*\ [, \*\*\ *metadata*] ) |
353 +------------------+----------------------------------------------------------+
354 | Method [3]_ | Method ([\*\*\ *metadata*] ) |
355 +------------------+----------------------------------------------------------+
356 | Module | Module ( [\*\*\ *metadata*] ) |
357 +------------------+----------------------------------------------------------+
358 | Password | Password( [*value* = '', *minlen* = 0, *maxlen* = |
359 | | sys.maxsize, *regex* = '', \*\*\ *metadata*] ) |
360 +------------------+----------------------------------------------------------+
361 | PrefixList | PrefixList( *values*\ [, \*\*\ *metadata*] ) |
362 +------------------+----------------------------------------------------------+
363 | PrefixMap | PrefixMap( *map*\ [, \*\*\ *metadata*] ) |
364 +------------------+----------------------------------------------------------+
365 | Property | Property( [*fget* = None, *fset* = None, *fvalidate* = |
366 | | None, *force* = False, *handler* = None, *trait* = None, |
367 | | \*\*\ *metadata*] ) |
368 | | |
369 | | See :ref:`property-traits`, for details. |
370 +------------------+----------------------------------------------------------+
371 | Python | Python ( [*value* = None, \*\*\ *metadata*] ) |
372 +------------------+----------------------------------------------------------+
373 | PythonValue | PythonValue( [*value* = None, \*\*\ *metadata*] ) |
374 +------------------+----------------------------------------------------------+
375 | Range | Range( [*low* = None, *high* = None, *value* = None, |
376 | | *exclude_low* = False, *exclude_high* = False, |
377 | | \*\ *metadata*] ) |
378 +------------------+----------------------------------------------------------+
379 | ReadOnly | ReadOnly( [*value* = Undefined, \*\*\ *metadata*] ) |
380 +------------------+----------------------------------------------------------+
381 | Regex | Regex( [*value* = '', *regex* = '.\*', \*\*\ *metadata*])|
382 +------------------+----------------------------------------------------------+
383 | self | n/a |
384 +------------------+----------------------------------------------------------+
385 | Set | Set( [*trait* = None, *value* = None, *items* = True, |
386 | | \*\*\ *metadata*] ) |
387 +------------------+----------------------------------------------------------+
388 | String | String( [*value* = '', *minlen* = 0, *maxlen* = |
389 | | sys.maxsize, *regex* = '', \*\*\ *metadata*] ) |
390 +------------------+----------------------------------------------------------+
391 | Subclass | Subclass( [*value* = None, *klass* = None, *allow_none* =|
392 | | True, \*\*\ *metadata*] ) |
393 +------------------+----------------------------------------------------------+
394 | This | n/a |
395 +------------------+----------------------------------------------------------+
396 | Time | Time( *value*\ [, *default_value* = None, |
397 | | *allow_none* = None, \*\*\ *metadata*]) |
398 +------------------+----------------------------------------------------------+
399 | ToolbarButton | ToolbarButton( [*label* = '', *image* = None, *style* = |
400 | | 'toolbar', *orientation* = 'vertical', *width_padding* = |
401 | | 2, *height_padding* = 2, \*\*\ *metadata*] ) |
402 +------------------+----------------------------------------------------------+
403 | Tuple | Tuple( [\*\ *traits*, \*\*\ *metadata*] ) |
404 +------------------+----------------------------------------------------------+
405 | Type | Type( [*value* = None, *klass* = None, *allow_none* = |
406 | | True, \*\*\ *metadata*] ) |
407 +------------------+----------------------------------------------------------+
408 | Union | Union( *val1*\ [, *val2*, ..., *valN*, |
409 | | \*\*\ *metadata*] ) |
410 +------------------+----------------------------------------------------------+
411 | UUID | UUID( [\*\*\ *metadata*] ) |
412 +------------------+----------------------------------------------------------+
413 | ValidatedTuple | ValidatedTuple( [\*\ *traits*, *fvalidate* = None, |
414 | | *fvalidate_info* = '' , \*\*\ *metadata*] ) |
415 +------------------+----------------------------------------------------------+
416 | WeakRef | WeakRef( [*klass* = 'traits.HasTraits', |
417 | | *allow_none* = False, *adapt* = 'yes', \*\*\ *metadata*])|
418 +------------------+----------------------------------------------------------+
419
420 .. index:: Instance trait
421
422 .. _instance:
423
424 Instance
425 ::::::::
426 One of the most fundamental and useful predefined trait types is
427 :class:`~.Instance`. Instance trait values are an instance of a particular class
428 or its subclasses, as specified by the **klass** argument. **klass** can be
429 either an instance of a class or a class itself (note this applies to all python
430 classes, not necessarily just :class:`~.HasTraits` subclasses). However, one should
431 typically provide the type or interface they want an instance of, instead of
432 providing an instance of a class.
433
434 If **klass** is an instance or if it is a class and **args** and **kw** are not
435 specified, the default value is ``None``. Otherwise, the default value is
436 obtained by calling the callable **factory** argument (or **klass** if
437 **factory** is None) with **args** and **kw**. Further, there is the
438 **allow_none** argument which dictates whether the trait can take on a value of
439 ``None``. However, this does not include the default value for the trait. For
440 example::
441
442 # instance_trait_defaults.py --- Example of Instance trait default values
443 from traits.api import HasTraits, Instance
444
445 class Parent(HasTraits):
446 pass
447
448 class Child(HasTraits):
449 # default value is None
450 father = Instance(Parent)
451 # default value is still None, but None can not be assigned
452 grandfather = Instance(Parent, allow_none=False)
453 # default value is Parent()
454 mother = Instance(Parent, args=())
455
456 In the last case, the default ``Parent`` instance is not immediately
457 created, but rather is lazily instantiated when the trait is first accessed.
458 The default ``Parent`` will also be instantiated if the trait is assigned to
459 and there is a change handler defined on the trait (to detect changes from the
460 default value). For more details on change handlers and trait notification see
461 :ref:`observe-notification`.
462
463 Somewhat surprisingly, ``mother = Instance(Parent, ())`` will also yield a
464 default value of ``Parent()``, even though in that case it is **factory** that
465 is ``()`` not **args**. This is a result of implementation details, however
466 the recommended way of writing this code is to explicitly pass **args** by
467 keyword like so ``mother = Instance(Parent, args=())``. Another common mistake
468 is passing in another trait type to Instance. For example,
469 ``some_trait = Instance(Int)``. This will likely lead to unexpected behavior
470 and potential errors. Instead simply do ``some_trait = Int()``.
471
472 .. index:: This trait, self trait
473
474 .. _this-and-self:
475
476 This and self
477 :::::::::::::
478 A couple of predefined traits that merit special explanation are This and
479 **self**. They are intended for attributes whose values must be of the same
480 class (or a subclass) as the enclosing class. The default value of This is
481 None; the default value of **self** is the object containing the attribute.
482
483 .. index::
484 pair: This trait; examples
485
486 The following is an example of using This::
487
488 # this.py --- Example of This predefined trait
489
490 from traits.api import HasTraits, This
491
492 class Employee(HasTraits):
493 manager = This
494
495 This example defines an Employee class, which has a **manager** trait
496 attribute, which accepts only other Employee instances as its value. It might
497 be more intuitive to write the following::
498
499 # bad_self_ref.py --- Non-working example with self- referencing
500 # class definition
501 from traits.api import HasTraits, Instance
502 class Employee(HasTraits):
503 manager = Instance(Employee)
504
505 However, the Employee class is not fully defined at the time that the
506 **manager** attribute is defined. Handling this common design pattern is the
507 main reason for providing the This trait.
508
509 Note that if a trait attribute is defined using This on one class and is
510 referenced on an instance of a subclass, the This trait verifies values based
511 on the class on which it was defined. For example::
512
513 >>> from traits.api import HasTraits, This
514 >>> class Employee(HasTraits):
515 ... manager = This
516 ...
517 >>> class Executive(Employee):
518 ... pass
519 ...
520 >>> fred = Employee()
521 >>> mary = Executive()
522 >>> # The following is OK, because fred's manager can be an
523 >>> # instance of Employee or any subclass.
524 >>> fred.manager = mary
525 >>> # This is also OK, because mary's manager can be an Employee
526 >>> mary.manager = fred
527
528 .. index:: Map trait
529
530 .. _map:
531
532 Map
533 :::
534 The map trait ensures that the value assigned to a trait attribute
535 is a key of a specified dictionary, and also assigns the dictionary
536 value corresponding to that key to a shadow attribute.
537
538 .. index::
539 pair: Map trait; examples
540
541 The following is an example of using Map::
542
543 # map.py --- Example of Map predefined trait
544
545 from traits.api import HasTraits, Map
546
547 class Person(HasTraits):
548 married = Map({'yes': 1, 'no': 0 }, default_value="yes")
549
550 This example defines a Person class which has a **married** trait
551 attribute which accepts values "yes" and "no". The default value
552 is set to "yes". The name of the shadow attribute is the name of
553 the Map attribute followed by an underscore, i.e ``married_``
554 Instantiating the class produces the following::
555
556 >>> from traits.api import HasTraits, Map
557 >>> bob = Person()
558 >>> print(bob.married)
559 yes
560 >>> print(bob.married_)
561 1
562
563 .. index:: PrefixMap trait
564
565 .. _prefixmap:
566
567 PrefixMap
568 :::::::::
569 Like Map, PrefixMap is created using a dictionary, but in this
570 case, the keys of the dictionary must be strings. Like PrefixList,
571 a string *v* is a valid value for the trait attribute if it is a prefix of
572 one and only one key *k* in the dictionary. The actual values assigned to
573 the trait attribute is *k*, and its corresponding mapped attribute is map[*k*].
574
575 .. index::
576 pair: PrefixMap trait; examples
577
578 The following is an example of using PrefixMap::
579
580 # prefixmap.py --- Example of PrefixMap predefined trait
581
582 from traits.api import HasTraits, PrefixMap
583
584 class Person(HasTraits):
585 married = PrefixMap({'yes': 1, 'no': 0 }, default_value="yes")
586
587 This example defines a Person class which has a **married** trait
588 attribute which accepts values "yes" and "no" or any unique
589 prefix. The default value is set to "yes". The name of the shadow attribute
590 is the name of the PrefixMap attribute followed by an underscore, i.e ``married_``
591 Instantiating the class produces the following::
592
593 >>> bob = Person()
594 >>> print(bob.married)
595 yes
596 >>> print(bob.married_)
597 1
598 >>> bob.married = "n" # Setting a prefix
599 >>> print(bob.married)
600 no
601 >>> print(bob.married_)
602 0
603
604 .. index:: PrefixList trait
605
606 .. _prefixlist:
607
608 PrefixList
609 ::::::::::
610 Ensures that a value assigned to the attribute is a member of a list of
611 specified string values, or is a unique prefix of one of those values.
612 The values that can be assigned to a trait attribute of type PrefixList
613 is the set of all strings supplied to the PrefixList constructor, as well
614 as any unique prefix of those strings. The actual value assigned to the
615 trait is limited to the set of complete strings assigned to the
616 PrefixList constructor.
617
618 .. index::
619 pair: PrefixList trait; examples
620
621 The following is an example of using PrefixList::
622
623 # prefixlist.py --- Example of PrefixList predefined trait
624
625 from traits.api import HasTraits, PrefixList
626
627 class Person(HasTraits):
628 married = PrefixList(["yes", "no"])
629
630 This example defines a Person class which has a **married** trait
631 attribute which accepts values "yes" and "no" or any unique
632 prefix. Instantiating the class produces the following::
633
634 >>> bob = Person()
635 >>> print(bob.married)
636 yes
637 >>> bob.married = "n" # Setting a prefix
638 >>> print(bob.married)
639 no
640
641 .. index:: Union trait
642
643 .. _union:
644
645 Union
646 :::::
647 The Union trait accepts a value that is considered valid by at least one
648 of the traits in its definition. It is a simpler and therefore less error-prone
649 alternative to the `Either` trait, which allows more complex constructs and
650 may sometimes exhibit mysterious validation behaviour. The Union trait however,
651 validates the value assigned to it against each of the traits in its definition
652 in the order they are defined. Union only accepts trait types or trait type
653 instances or None in its definition. Prefer to use Union over `Either` to
654 remain future proof.
655
656 .. index::
657 pair: Union trait; examples
658
659 The following is an example of using Union::
660
661 # union.py --- Example of Union predefined trait
662
663 from traits.api import HasTraits, Union, Int, Float, Instance
664
665 class Salary(HasTraits):
666 basic = Float
667 bonus = Float
668
669 class Employee(HasTraits):
670 manager_name = Union(Str, None)
671 pay = Union(Instance(Salary), Float)
672
673 This example defines an Employee class, which has a **manager_name** trait
674 attribute, which accepts either an Str instance or None as its value, a
675 **salary** trait that accepts an instance of Salary or Float and will raise a
676 TraitError if a value of any other type is assigned. For example::
677
678 >>> from traits.api import HasTraits, Str, Union
679 >>> class Employee(HasTraits):
680 ... manager_name = Union(Str, None)
681 ...
682 >>> steven = Employee(manager_name="Jenni")
683 >>> # Here steven's manager is named "Jenni"
684 >>> # Assigning a value that is neither a string nor None will fail.
685 >>> steven.manager_name = 5
686 traits.trait_errors.TraitError: The 'manager_name' trait of an Employee instance must be a string or a None type, but a value of 5 <class 'int'> was specified.
687
688 The following example illustrates the difference between `Either` and `Union`::
689
690 >>> from traits.api import Either, HasTraits, Str, Union
691 >>> class IntegerClass(HasTraits):
692 ... primes = Either([2], None, {'3':6}, 5, 7, 11)
693 ...
694 >>> i = IntegerClass(primes=2) # Acceptable value, no error
695 >>> i = IntegerClass(primes=4)
696 traits.trait_errors.TraitError: The 'primes' trait of an IntegerClass instance must be 2 or None or 5 or 7 or 11 or '3', but a value of 4 <class 'int'> was specified.
697 >>>
698 >>> # But Union does not allow such declarations.
699 >>> class IntegerClass(HasTraits):
700 ... primes = Union([2], None, {'3':6}, 5, 7, 11)
701 ValueError: Union trait declaration expects a trait type or an instance of trait type or None, but got [2] instead
702
703 .. index:: Either trait
704
705 .. _either:
706
707 Either
708 ::::::
709
710 .. note::
711 The :class:`~.Either` trait type may eventually be deprecated, and should
712 not be used in new code. Use the more well-behaved :class:`~.Union` trait
713 type instead.
714
715 Another predefined trait that merits special explanation is Either. The
716 Either trait is intended for attributes that may take a value of more than
717 a single trait type, including None. The default value of Either is None, even
718 if None is not one of the types the user explicitly defines in the constructor,
719 but a different default value can be provided using the ``default`` argument.
720
721 .. index::
722 pair: Either trait; examples
723
724 The following is an example of using Either::
725
726 # either.py --- Example of Either predefined trait
727
728 from traits.api import HasTraits, Either, Str
729
730 class Employee(HasTraits):
731 manager_name = Either(Str, None)
732
733 This example defines an Employee class, which has a **manager_name** trait
734 attribute, which accepts either an Str instance or None as its value, and
735 will raise a TraitError if a value of any other type is assigned. For example::
736
737 >>> from traits.api import HasTraits, Either, Str
738 >>> class Employee(HasTraits):
739 ... manager_name = Either(Str, None)
740 ...
741 >>> steven = Employee(manager_name="Jenni")
742 >>> # Here steven's manager is named "Jenni"
743 >>> steven.manager_name
744 'Jenni'
745 >>> eric = Employee(manager_name=None)
746 >>> # Eric is the boss, so he has no manager.
747 >>> eric.manager_name is None
748 True
749 >>> # Assigning a value that is neither a string nor None will fail.
750 >>> steven.manager_name = 5
751 traits.trait_errors.TraitError: The 'manager_name' trait of an Employee instance must be a string or None, but a value of 5 <type 'int'> was specified.
752
753
754 .. _migration_either_to_union:
755
756 .. rubric:: Migration from Either to Union
757
758 * Static default values are defined on Union via the **default_value**
759 attribute, whereas Either uses the **default** attribute. The naming of
760 **default_value** is consistent with other trait types.
761 For example::
762
763 Either(None, Str(), default="unknown")
764
765 would be changed to::
766
767 Union(None, Str(), default_value="unknown")
768
769 * If a default value is not defined, Union uses the default value from the
770 first trait in its definition, whereas Either uses None.
771
772 For example::
773
774 Either(Int(), Float())
775
776 has a default value of None. However None is not one of the allowed values.
777 If the trait is later set to None from a non-None value, a validation error
778 will occur.
779
780 If the trait definition is changed to::
781
782 Union(Int(), Float())
783
784 Then the default value will be 0, which is the default value of the first
785 trait.
786
787 To keep None as the default, use None as the first item::
788
789 Union(None, Int(), Float())
790
791 With this, None also becomes one of the allowed values.
792
793 .. index:: multiple values, defining trait with
794
795 .. _list-of-possibl-values:
796
797 List of Possible Values
798 :::::::::::::::::::::::
799 You can define a trait whose possible values include disparate types. To do
800 this, use the predefined Enum trait, and pass it a list of all possible values.
801 The values must all be of simple Python data types, such as strings, integers,
802 and floats, but they do not have to be all of the same type. This list of
803 values can be a typical parameter list, an explicit (bracketed) list, or a
804 variable whose type is list. The first item in the list is used as the default
805 value.
806
807 .. index:: examples; list of values
808
809 A trait defined in this fashion can accept only values that are contained in
810 the list of permitted values. The default value is the first value specified;
811 it is also a valid value for assignment.
812 ::
813
814 >>> from traits.api import Enum, HasTraits, Str
815 >>> class InventoryItem(HasTraits):
816 ... name = Str # String value, default is ''
817 ... stock = Enum(None, 0, 1, 2, 3, 'many')
818 ... # Enumerated list, default value is
819 ... #'None'
820 ...
821 >>> hats = InventoryItem()
822 >>> hats.name = 'Stetson'
823
824 >>> print('%s: %s' % (hats.name, hats.stock))
825 Stetson: None
826
827 >>> hats.stock = 2 # OK
828 >>> hats.stock = 'many' # OK
829 >>> hats.stock = 4 # Error, value is not in \
830 >>> # permitted list
831 Traceback (most recent call last):
832 ...
833 traits.trait_errors.TraitError: The 'stock' trait of an InventoryItem
834 instance must be None or 0 or 1 or 2 or 3 or 'many', but a value of 4
835 <type 'int'> was specified.
836
837
838 This defines an :py:class:`InventoryItem` class, with two trait attributes,
839 **name**, and **stock**. The name attribute is simply a string. The **stock**
840 attribute has an initial value of None, and can be assigned the values None, 0,
841 1, 2, 3, and 'many'. The example then creates an instance of the InventoryItem
842 class named **hats**, and assigns values to its attributes.
843
844 When the list of possible values can change during the lifetime of the object,
845 one can specify **another trait** that holds the list of possible values::
846
847 >>> from traits.api import Enum, HasTraits, List
848 >>> class InventoryItem(HasTraits):
849 ... possible_stock_states = List([None, 0, 1, 2, 3, 'many'])
850 ... stock = Enum(0, values="possible_stock_states")
851 ... # Enumerated list, default value is 0. The list of
852 ... # allowed values is whatever possible_stock_states holds
853 ...
854
855 >>> hats = InventoryItem()
856 >>> hats.stock
857 0
858 >>> hats.stock = 2 # OK
859 >>> hats.stock = 4 # TraitError like above
860 Traceback (most recent call last):
861 ...
862 traits.trait_errors.TraitError: The 'stock' trait of an InventoryItem
863 instance must be None or 0 or 1 or 2 or 3 or 'many', but a value of 4
864 <type 'int'> was specified.
865
866 >>> hats.possible_stock_states.append(4) # Add 4 to list of allowed values
867 >>> hats.stock = 4 # OK
868
869
870 .. index:: metadata attributes; on traits
871
872 .. _trait-metadata:
873
874 Trait Metadata
875 --------------
876 Trait objects can contain metadata attributes, which fall into three categories:
877
878 * Internal attributes, which you can query but not set.
879 * Recognized attributes, which you can set to determine the behavior of the
880 trait.
881 * Arbitrary attributes, which you can use for your own purposes.
882
883 You can specify values for recognized or arbitrary metadata attributes by
884 passing them as keyword arguments to callable traits. The value of each
885 keyword argument becomes bound to the resulting trait object as the value
886 of an attribute having the same name as the keyword.
887
888 .. index:: metadata attributes; internal
889
890 .. _internal-metadata-attributes:
891
892 Internal Metadata Attributes
893 ````````````````````````````
894 The following metadata attributes are used internally by the Traits package,
895 and can be queried:
896
897 .. index:: array metadata attribute, default metadata attribute
898 .. index:: default_kind metadata attribute, delegate; metadata attribute
899 .. index:: inner_traits metadata attribute, parent metadata attribute
900 .. index:: prefix metadata attribute, trait_type metadata attribute
901 .. index:: type metadata attribute
902
903 * **array**: Indicates whether the trait is an array.
904 * **default**: Returns the default value for the trait, if known; otherwise it
905 returns Undefined.
906 * **default_kind**: Returns a string describing the type of value returned by
907 the default attribute for the trait. The possible values are:
908
909 * ``value``: The default attribute returns the actual default value.
910 * ``list``: A copy of the list default value.
911 * ``dict``: A copy of the dictionary default value.
912 * ``self``: The default value is the object the trait is bound to; the
913 **default** attribute returns Undefined.
914 * ``factory``: The default value is created by calling a factory; the
915 **default** attribute returns Undefined.
916 * ``method``: The default value is created by calling a method on the object
917 the trait is bound to; the **default** attribute returns Undefined.
918
919 * **delegate**: The name of the attribute on this object that references the
920 object that this object delegates to.
921 * **inner_traits**: Returns a tuple containing the "inner" traits
922 for the trait. For most traits, this is empty, but for List and Dict traits,
923 it contains the traits that define the items in the list or the keys and
924 values in the dictionary.
925 * **parent**: The trait from which this one is derived.
926 * **prefix**: A prefix or substitution applied to the delegate attribute.
927 See :ref:`deferring-traits` for details.
928 * **trait_type**: Returns the type of the trait, which is typically a handler
929 derived from TraitType.
930 * **type**: One of the following, depending on the nature of the trait:
931
932 * ``constant``
933 * ``delegate``
934 * ``event``
935 * ``property``
936 * ``trait``
937
938 .. index:: recognized metadata attributes, metadata attributes; recognized
939
940 .. _recognized-metadata-attributes:
941
942 Recognized Metadata Attributes
943 ``````````````````````````````
944 The following metadata attributes are not predefined, but are recognized by
945 HasTraits objects:
946
947 .. index:: desc metadata attribute, editor metadata attribute
948 .. index:: label; metadata attribute, comparison_mode metadata attribute
949 .. index:: transient metadata attribute
950
951 * **desc**: A string describing the intended meaning of the trait. It is used
952 in exception messages and fly-over help in user interface trait editors.
953 * **editor**: Specifies an instance of a subclass of TraitEditor to use when
954 creating a user interface editor for the trait. Refer to the
955 `TraitsUI User Manual
956 <http://docs.enthought.com/traitsui/traitsui_user_manual/index.html>`_
957 for more information on trait editors.
958 * **label**: A string providing a human-readable name for the trait. It is
959 used to label trait attribute values in user interface trait editors.
960 * **comparison_mode**: Indicates when trait change notifications should be
961 generated based upon the result of comparing the old and new values of a
962 trait assignment. This should be a member of the
963 :class:`~traits.constants.ComparisonMode` enumeration class.
964 * **transient**: A Boolean indicating that the trait value is not persisted
965 when the object containing it is persisted. The default value for most
966 predefined traits is False (the value will be persisted if its container is).
967 You can set it to True for traits whose values you know you do not want to
968 persist. Do not set it to True on traits where it is set internally to
969 False, as doing so is likely to create unintended consequences. See
970 :ref:`persistence` for more information.
971
972 Other metadata attributes may be recognized by specific predefined traits.
973
974 .. index:: metadata attributes; accessing
975
976 .. _accessing-metadata-attributes:
977
978 Accessing Metadata Attributes
979 `````````````````````````````
980 .. index::
981 pair: examples; metadata attributes
982
983 Here is an example of setting trait metadata using keyword arguments::
984
985 # keywords.py --- Example of trait keywords
986 from traits.api import HasTraits, Str
987
988 class Person(HasTraits):
989 first_name = Str('',
990 desc='first or personal name',
991 label='First Name')
992 last_name = Str('',
993 desc='last or family name',
994 label='Last Name')
995
996 In this example, in a user interface editor for a Person object, the labels
997 "First Name" and "Last Name" would be used for entry
998 fields corresponding to the **first_name** and **last_name** trait attributes.
999 If the user interface editor supports rollover tips, then the **first_name**
1000 field would display "first or personal name" when the user moves
1001 the mouse over it; the last_name field would display "last or family
1002 name" when moused over.
1003
1004 To get the value of a trait metadata attribute, you can use the trait() method
1005 on a HasTraits object to get a reference to a specific trait, and then access
1006 the metadata attribute::
1007
1008 # metadata.py --- Example of accessing trait metadata attributes
1009 from traits.api import HasTraits, Int, List, Float, Str, \
1010 Instance, Any, TraitType
1011
1012 class Foo( HasTraits ): pass
1013
1014 class Test( HasTraits ):
1015 i = Int(99)
1016 lf = List(Float)
1017 foo = Instance( Foo, () )
1018 any = Any( "123" )
1019
1020 t = Test()
1021
1022 print(t.trait( 'i' ).default) # 99
1023 print(t.trait( 'i' ).default_kind) # value
1024 print(t.trait( 'i' ).inner_traits) # ()
1025 print(t.trait( 'i' ).is_trait_type( Int )) # True
1026 print(t.trait( 'i' ).is_trait_type( Float )) # False
1027
1028 print(t.trait( 'lf' ).default) # []
1029 print(t.trait( 'lf' ).default_kind) # list
1030 print(t.trait( 'lf' ).inner_traits)
1031 # (<traits.traits.CTrait object at 0x01B24138>,)
1032 print(t.trait( 'lf' ).is_trait_type( List )) # True
1033 print(t.trait( 'lf' ).is_trait_type( TraitType )) # True
1034 print(t.trait( 'lf' ).is_trait_type( Float )) # False
1035 print(t.trait( 'lf' ).inner_traits[0].is_trait_type( Float )) # True
1036
1037 print(t.trait( 'foo' ).default) # <undefined>
1038 print(t.trait( 'foo' ).default_kind) # factory
1039 print(t.trait( 'foo' ).inner_traits) # ()
1040 print(t.trait( 'foo' ).is_trait_type( Instance )) # True
1041 print(t.trait( 'foo' ).is_trait_type( List )) # False
1042
1043 print(t.trait( 'any' ).default) # 123
1044 print(t.trait( 'any' ).default_kind) # value
1045 print(t.trait( 'any' ).inner_traits) # ()
1046 print(t.trait( 'any' ).is_trait_type( Any )) # True
1047 print(t.trait( 'any' ).is_trait_type( Str )) # False
1048
1049 .. rubric:: Footnotes
1050 .. [1] Most callable predefined traits are classes, but a few are functions.
1051 The distinction does not make a difference unless you are trying to
1052 extend an existing predefined trait. See the *Traits API Reference* for
1053 details on particular traits, and see Chapter 5 for details on extending
1054 existing traits.
1055 .. [2] The :class:`~.Either` trait type is likely to be deprecated at some
1056 point in the future. The :class:`~.Union` trait type should be preferred
1057 to :class:`~.Either` in new code.
1058 .. [3] The Function and Method trait types are now deprecated. See |Function|,
1059 |Method|
1060
1061 ..
1062 external urls
1063
1064 .. _Traits bug tracker: https://github.com/enthought/traits/issues
1065
1066 ..
1067 # substitutions
1068
1069 .. |Function| replace:: :class:`~traits.trait_types.Function`
1070 .. |Method| replace:: :class:`~traits.trait_types.Method`