Debian Codegraph @

docs/source/traits_user_manual/advanced.rst

raw
1 .. _advanced-topics:
2
3 ===============
4 Advanced Topics
5 ===============
6
7 The preceding sections provide enough information for you to use traits for
8 manifestly-typed attributes, with initialization and validation. This section
9 describes the advanced features of the Traits package
10
11 .. _initialization-and-validation-revisited:
12
13 Initialization and Validation Revisited
14 ---------------------------------------
15
16 The following sections present advanced topics related to the initialization and
17 validation features of the Traits package.
18
19 * Dynamic initialization
20 * Overriding default values
21 * Reusing trait definitions
22 * Trait attribute definition strategies
23
24 .. index:: initialization; dynamic
25
26 .. _dynamic-initialization:
27
28 Dynamic Initialization
29 ``````````````````````
30
31 When you define trait attributes using predefined traits, the Trait() factory
32 function or trait handlers, you typically specify their default values
33 statically. You can also define a method that dynamically initializes a trait
34 attribute. To do this, you define a method on the same class as the trait
35 attribute, with a name based on the name of the trait attribute:
36
37 .. index:: default value; method
38
39 .. method:: _name_default()
40
41 This method returns the default value for the *name* trait attribute and it
42 overrides any default value specified in the trait definition.
43
44 Similar to static default values, default values defined dynamically should be
45 thought of as existing **prior to** setting object state during
46 initialization. For performance purposes, a default initializer method is
47 called when:
48
49 1. the attribute value is accessed the first time or
50 2. an instance is constructed with a specific value, if there is a change
51 handler defined for the trait. This is needed so the default can be reported
52 as the old value (see :ref:`static-notification`).
53
54 While it is possible to use a default initializer method to lazily initialize
55 attributes based on the object state post-instantiation, this relies on not
56 having to observe for changes on the trait. This is often difficult in
57 practice, since trait notifications can be set up by external objects, and are
58 often needed for Property traits, delegation and GUI applications. These use
59 cases may cause the default values to be computed eagerly prior to
60 instantiation, instead of lazily after instantiation.
61
62 .. index:: get_default_value()
63
64 It is also possible to define a dynamic method for the default value in a trait
65 type subclass (get_default_value()). However, using a
66 _\ *name*\ _default() method avoids the overhead of subclassing a trait.
67
68 .. index:: default value; overriding in a subclass
69 .. index::
70 pair: examples; overriding default values
71
72 .. _overriding-default-values-in-a-subclass:
73
74 Overriding Default Values in a Subclass
75 ```````````````````````````````````````
76
77 Often, a subclass must override a trait attribute in a parent class by providing
78 a different default value. You can specify a new default value without
79 completely re-specifying the trait definition for the attribute. For example::
80
81 # override_default.py -- Example of overriding a default value for
82 # a trait attribute in a subclass
83 from traits.api import HasTraits, Range, Str
84
85 class Employee(HasTraits):
86 name = Str
87 salary_grade = Range(value=1, low=1, high=10)
88
89 class Manager(Employee):
90 salary_grade = 5
91
92 In this example, the **salary_grade** of the Employee class is a range from 1 to
93 10, with a default value of 1. In the Manager subclass, the default value of
94 **salary_grade** is 5, but it is still a range as defined in the Employee class.
95
96 .. index:: trait; definitions; reusing
97
98 .. _reusing-trait-definitions:
99
100 Reusing Trait Definitions
101 `````````````````````````
102
103 As mentioned in :ref:`defining-traits-initialization-and-validation`, in most
104 cases, traits are defined in-line in attribute definitions, but they can also be
105 defined independently. A trait definition only describes the characteristics of
106 a trait, and not the current value of a trait attribute, so it can be used in
107 the definition of any number of attributes. For example::
108
109 # trait_reuse.py --- Example of reusing trait definitions
110 from traits.api import HasTraits, Range
111
112 coefficient = Range(-1.0, 1.0, 0.0))
113
114 class quadratic(HasTraits):
115 c2 = coefficient
116 c1 = coefficient
117 c0 = coefficient
118 x = Range(-100.0, 100.0, 0.0)
119
120 In this example, a trait named **coefficient** is defined externally to the
121 class **quadratic**, which references **coefficient** in the definitions of its
122 trait attributes **c2**, **c1**, and **c0**. Each of these attributes has a
123 unique value, but they all use the same trait definition to determine whether a
124 value assigned to them is valid.
125
126 .. index:: explicit trait attribute definition
127
128 .. _trait-attribute-definition-strategies:
129
130 Trait Attribute Definition Strategies
131 `````````````````````````````````````
132
133 In the preceding examples in this guide, all trait attribute definitions have
134 bound a single object attribute to a specified trait definition. This is known
135 as "explicit" trait attribute definition. The Traits package supports other
136 strategies for defining trait attributes. You can associate a category of
137 attributes with a particular trait definition, using the trait attribute name
138 wildcard. You can also dynamically create trait attributes that are specific to
139 an instance, using the add_trait() method, rather than defined on a class. These
140 strategies are described in the following sections.
141
142 .. index:: wildcard; trait attribute names
143 pair: wildcard; examples
144
145 .. _trait-attribute-name-wildcard:
146
147 Trait Attribute Name Wildcard
148 :::::::::::::::::::::::::::::
149
150 The Traits package enables you to define a category of trait attributes
151 associated with a particular trait definition, by including an underscore ('_')
152 as a wildcard at the end of a trait attribute name. For example::
153
154 # temp_wildcard.py --- Example of using a wildcard with a Trait
155 # attribute name
156 from traits.api import Any, HasTraits
157
158 class Person(HasTraits):
159 temp_ = Any
160
161 This example defines a class Person, with a category of attributes that have
162 names beginning with ``temp``, and that are defined by the Any trait. Thus, any
163 part of the program that uses a Person instance can reference attributes such as
164 **tempCount**, **temp_name**, or **temp_whatever**, without having to explicitly
165 declare these trait attributes. Each such attribute has None as the initial
166 value and allows assignment of any value (because it is based on the Any trait).
167
168 You can even give all object attributes a default trait definition, by
169 specifying only the wildcard character for the attribute name::
170
171 # all_wildcard.py --- Example of trait attribute wildcard rules
172 from traits.api import Any, HasTraits, Int, Str
173
174 class Person ( HasTraits ):
175
176 # Normal, explicitly defined trait:
177 name = Str
178
179 # By default, let all traits have any value:
180 _ = Any
181
182 # Except for this one, which must be an Int:
183 age = Int
184 """
185 >>> bill = Person()
186 >>> # These assignments should all work:
187 >>> bill.name = 'William'
188 >>> bill.address = '121 Drury Lane'
189 >>> bill.zip_code = 55212
190 >>> bill.age = 49
191 >>> # This should generate an error (must be an Int):
192 >>> bill.age = 'middle age'
193 Traceback (most recent call last):
194 File "all_wildcard.py", line 33, in <module>
195 bill.age = 'middle age'
196 File "c:\wrk\src\lib\enthought\traits\\trait_handlers.py", line 163, in error
197 raise TraitError( object, name, self.info(), value )
198 TraitError: The 'age' trait of a Person instance must be an integer, but a value
199 of 'middle age' <type 'str'> was specified.
200 """
201
202 In this case, all Person instance attributes can be created on the fly and are
203 defined by the Any trait.
204
205 .. index:: wildard; rules
206
207 .. _wildcard-rules:
208
209 Wildcard Rules
210 ''''''''''''''
211
212 When using wildcard characters in trait attribute names, the following rules are
213 used to determine what trait definition governs an attribute:
214
215 1. If an attribute name exactly matches a name without a wildcard character,
216 that definition applies.
217 2. Otherwise, if an attribute name matches one or more names with wildcard
218 characters, the definition with the longest name applies.
219
220 Note that all possible attribute names are covered by one of these two rules.
221 The base HasTraits class implicitly contains the attribute definition
222 ``_ = Python``. This rule guarantees that, by default, all attributes have
223 standard Python language semantics.
224
225 These rules are demonstrated by the following example::
226
227 # wildcard_rules.py -- Example of trait attribute wildcard rules
228 from traits.api import Any, HasTraits, Int, Python
229
230 class Person(HasTraits):
231 temp_count = Int(-1)
232 temp_ = Any
233 _ = Python
234
235 In this example, the Person class has a **temp_count** attribute, which must be
236 an integer and which has an initial value of -1. Any other attribute with a name
237 starting with ``temp`` has an initial value of None and allows any value to be
238 assigned. All other object attributes behave like normal Python attributes
239 (i.e., they allow any value to be assigned, but they must have a value assigned
240 to them before their first reference).
241
242 .. index:: Disallow; object, examples; Disallow object
243
244 .. _disallow-object:
245
246 Disallow Object
247 '''''''''''''''
248
249 The singleton object Disallow can be used with wildcards to disallow all
250 attributes that are not explicitly defined. For example::
251
252 # disallow.py --- Example of using Disallow with wildcards
253 from traits.api import \
254 Disallow, Float, HasTraits, Int, Str
255
256 class Person (HasTraits):
257 name = Str
258 age = Int
259 weight = Float
260 _ = Disallow
261
262 In this example, a Person instance has three trait attributes:
263
264 * **name**: Must be a string; its initial value is ''.
265 * **age**: Must be an integer; its initial value is 0.
266 * **weight**: Must be a float; its initial value is 0.0.
267
268 All other object attributes are explicitly disallowed. That is, any attempt to
269 read or set any object attribute other than **name**, **age**, or **weight**
270 causes an exception.
271
272 .. index:: HasTraits class; predefined subclasses
273
274 .. _hastraits-subclasses:
275
276 HasTraits Subclasses
277 ''''''''''''''''''''
278
279 Because the HasTraits class implicitly contains the attribute definition
280 ``_ = Python``, subclasses of HasTraits by default have very standard Python
281 attribute behavior for any attribute not explicitly defined as a trait
282 attribute. However, the wildcard trait attribute definition rules make it easy
283 to create subclasses of HasTraits with very non-standard attribute behavior. Two
284 such subclasses are predefined in the Traits package: HasStrictTraits and
285 HasPrivateTraits.
286
287 .. index:: HasStrictTraits class
288
289 .. _hasstricttraits:
290
291 HasStrictTraits
292 '''''''''''''''
293
294 This class guarantees that accessing any object attribute that does not have an
295 explicit or wildcard trait definition results in an exception. This can be
296 useful in cases where a more rigorous software engineering approach is employed
297 than is typical for Python programs. It also helps prevent typos and spelling
298 mistakes in attribute names from going unnoticed; a misspelled attribute name
299 typically causes an exception. The definition of HasStrictTraits is the
300 following::
301
302 class HasStrictTraits(HasTraits):
303 _ = Disallow
304
305 HasStrictTraits can be used to create type-checked data structures, as in the
306 following example::
307
308 class TreeNode(HasStrictTraits):
309 left = This
310 right = This
311 value = Str
312
313 This example defines a TreeNode class that has three attributes: **left**,
314 **right**, and **value**. The **left** and **right** attributes can only be
315 references to other instances of TreeNode (or subclasses), while the **value**
316 attribute must be a string. Attempting to set other types of values generates an
317 exception, as does attempting to set an attribute that is not one of the three
318 defined attributes. In essence, TreeNode behaves like a type-checked data
319 structure.
320
321 .. index:: HasRequiredTraits class
322
323 .. _hasrequiredtraits:
324
325 HasRequiredTraits
326 '''''''''''''''''
327
328 This subclass of :ref:`hasstricttraits` ensures that any object attribute with
329 ``required=True`` in its metadata must be passed as an argument on object
330 initialization.
331
332 An example of a class with required traits::
333
334 class RequiredTest(HasRequiredTraits):
335 required_trait = Any(required=True)
336 non_required_trait = Any()
337
338 All required traits have to be provided as arguments on creating a new
339 instance::
340
341 >>> new_instance = RequiredTest(required_trait=13.0)
342
343 Non-required traits can also still be provided as usual::
344
345 >>> new_instance = RequiredTest(required_trait=13.0, non_required_trait=14.0)
346
347 However, omitting a required trait will raise a TraitError::
348
349 >>> new_instance = RequiredTest(non_required_trait=14.0)
350 traits.trait_errors.TraitError: The following required traits were not
351 provided: required_trait.
352
353 .. index:: HasPrivateTraits class
354
355 .. _hasprivatetraits:
356
357 HasPrivateTraits
358 ''''''''''''''''
359
360 This class is similar to HasStrictTraits, but allows attributes beginning with
361 '_' to have an initial value of None, and to not be type-checked. This is useful
362 in cases where a class needs private attributes, which are not part of the
363 class's public API, to keep track of internal object state. Such attributes do
364 not need to be type-checked because they are only manipulated by the (presumably
365 correct) methods of the class itself. The definition of HasPrivateTraits is the
366 following::
367
368 class HasPrivateTraits(HasTraits):
369 __ = Any
370 _ = Disallow
371
372 These subclasses of HasTraits are provided as a convenience, and their use is
373 completely optional. However, they do illustrate how easy it is to create
374 subclasses with customized default attribute behavior if desired.
375
376 .. index:: trait attributes; per-object
377
378 .. _per-object-trait-attributes:
379
380 Per-Object Trait Attributes
381 '''''''''''''''''''''''''''
382
383 The Traits package allows you to define dynamic trait attributes that are
384 object-, rather than class-, specific. This is accomplished using the
385 add_trait() method of the HasTraits class:
386
387 .. method:: add_trait(name, trait)
388
389 .. index:: examples; per-object trait attributes
390
391 For example::
392
393 # object_trait_attrs.py --- Example of per-object trait attributes
394 from traits.api import HasTraits, Range
395
396 class GUISlider (HasTraits):
397
398 def __init__(self, eval=None, label='Value',
399 trait=None, min=0.0, max=1.0,
400 initial=None, **traits):
401 HasTraits.__init__(self, **traits)
402 if trait is None:
403 if min > max:
404 min, max = max, min
405 if initial is None:
406 initial = min
407 elif not (min <= initial <= max):
408 initial = [min, max][
409 abs(initial - min) >
410 abs(initial - max)]
411 trait = Range(min, max, value = initial)
412 self.add_trait(label, trait)
413
414 This example creates a GUISlider class, whose __init__() method can accept a
415 string label and either a trait definition or minimum, maximum, and initial
416 values. If no trait definition is specified, one is constructed based on the
417 **max** and **min** values. A trait attribute whose name is the value of label
418 is added to the object, using the trait definition (whether specified or
419 constructed). Thus, the label trait attribute on the GUISlider object is
420 determined by the calling code, and added in the __init__() method using
421 add_trait().
422
423 You can require that add_trait() must be used in order to add attributes to a
424 class, by deriving the class from HasStrictTraits (see :ref:`hasstricttraits`).
425 When a class inherits from HasStrictTraits, the program cannot create a new
426 attribute (either a trait attribute or a regular attribute) simply by assigning
427 to it, as is normally the case in Python. In this case, add_trait() is the only
428 way to create a new attribute for the class outside of the class definition.
429
430
431 .. index:: interfaces
432
433 .. _interfaces:
434
435 Interfaces
436 ----------
437
438 The Traits package supports declaring and implementing
439 *interfaces*. An interface is an abstract data type that defines a set of
440 attributes and methods that an object must have to work in a given situation.
441 The interface says nothing about what the attributes or methods do, or how they
442 do it; it just says that they have to be there. Interfaces in Traits are similar
443 to those in Java. They can be used to declare a relationship among classes which
444 have similar behavior but do not have an inheritance relationship. Like Traits
445 in general, Traits interfaces don't make anything possible that is not already
446 possible in Python, but they can make relationships more explicit and enforced.
447 Python programmers routinely use implicit, informal interfaces (what's known as
448 "duck typing"). Traits allows programmers to define explicit and formal
449 interfaces, so that programmers reading the code can more easily understand what
450 kinds of objects are actually *intended* to be used in a given situation.
451
452 .. index:: interfaces; defining, examples; interface definition
453
454 .. _defining-an-interface:
455
456 Defining an Interface
457 `````````````````````
458
459 To define an interface, create a subclass of Interface::
460
461 from traits.api import Interface
462
463 class IName(Interface):
464
465 def get_name(self):
466 """ Returns a string which is the name of an object. """
467
468 Interface classes serve primarily as documentation of the methods and
469 attributes that the interface defines. In this case, a class that implements the
470 ``IName`` interface must have a method named ``get_name()``, which takes no arguments
471 and returns a string. Do not include any implementation code in an interface
472 declaration. However, the Traits package does not actually check to ensure that
473 interfaces do not contain implementations.
474
475 By convention, interface names have a capital 'I' at the beginning of the name.
476
477 .. index:: interfaces; implementing
478
479 .. _implementing-an-interface:
480
481 Implementing an Interface
482 `````````````````````````
483
484 A class declares that it implements one or more interfaces using the
485 :func:`~traits.api.provides` class decorator, which has the signature:
486
487 .. currentmodule:: traits.has_traits
488 .. function:: provides(interface[, interface2 , ... , interfaceN])
489 :noindex:
490
491 .. index:: examples; interface implementation, interfaces; implementation; example
492
493 Interface names beyond the first one are optional. As for all class
494 decorators, the call to provides must occur just before the class
495 definition. For example::
496
497 from traits.api import HasTraits, Interface, provides, Str
498
499 class IName(Interface):
500 def get_name(self):
501 """ Returns a string which is the name of an object. """
502
503 @provides(IName)
504 class Person(HasTraits):
505
506 first_name = Str( 'John' )
507 last_name = Str( 'Doe' )
508
509 # Implementation of the 'IName' interface:
510 def get_name ( self ):
511 ''' Returns the name of an object. '''
512 name = '{first} {last}'
513 return name.format(name=self.first_name, last=self.last_name)
514
515 You can specify whether the provides() decorator verifies that
516 the class calling it actually implements the interface that it says it does.
517 This is determined by the CHECK_INTERFACES variable, which can take one of three
518 values:
519
520 * 0 (default): Does not check whether classes implement their declared interfaces.
521 * 1: Verifies that classes implement the interfaces they say they do, and logs
522 a warning if they don't.
523 * 2: Verifies that classes implement the interfaces they say they do, and raises
524 an InterfaceError if they don't.
525
526 The CHECK_INTERFACES variable must be imported directly from the
527 traits.has_traits module::
528
529 import traits.has_traits
530 traits.has_traits.CHECK_INTERFACES = 1
531
532 .. deprecated:: 6.2.0
533 Interface checking with the ``@provides`` decorator is deprecated. In the
534 future, the ``@provides`` decorator will ignore the value of
535 ``CHECK_INTERFACES`` and will not do any interface checking.
536
537 .. index:: interfaces; using, examples; interface usage
538
539 .. _using-interfaces:
540
541 Using Interfaces
542 ````````````````
543
544 You can use an interface at any place where you would normally use a class name.
545 The most common way to use interfaces is with the
546 :class:`~traits.trait_types.Instance` or
547 :class:`~traits.trait_types.Supports` traits::
548
549 >>> from traits.api import HasTraits, Instance
550 >>> class Apartment(HasTraits):
551 ... renter = Instance(IName)
552 >>> william = Person(first_name='William', last_name='Adams')
553 >>> apt1 = Apartment( renter=william )
554 >>> print 'Renter is: ', apt1.renter.get_name()
555 Renter is: William Adams
556
557 Using an interface class with an ``Instance`` trait definition declares that the
558 trait accepts only values that implement the specified interface. Using the
559 ``Supports`` traits, if the assigned object does not implement the interface,
560 the Traits package may automatically substitute an adapter object that
561 implements the specified interface. See :ref:`adaptation` for more
562 information.
563
564 .. index:: adaptation
565
566 .. _adaptation:
567
568 Adaptation
569 ----------
570
571 *The adaptation features of Traits have been rewritten in v. 4.4.0 . See
572 the* :ref:`migration guide <migration>` *below for details regarding changes
573 in API.*
574
575 Adaptation is the process of transforming an object that does not implement a
576 specific interface needed by a client into an object that does. In the adapter
577 pattern, an object is wrapped in a second object, the *adapter*,
578 that implements the target interface.
579
580 Adaptation enables a programming style in which each component or service in an
581 application defines an interface through which it would like to receive
582 information. Objects that need to communicate with the component declare
583 an adapter for that interface, as illustrated in the figure below.
584
585 .. image:: images/adaptation.png
586
587 Adaptation allows decoupling the data model from the application components and
588 services: introducing a new component in the application should not require
589 modifying the data objects!
590
591 Traits provides a package to make this pattern easy and automatic:
592 In the :mod:`traits.adaptation` package, adapters from a protocol
593 (type or interface) to another can be registered with a manager object.
594 HasTraits classes can either explicitly request to adapt an object to a
595 protocol, or they can define special traits that automatically invoke
596 the adaptation manager whenever it is necessary.
597
598 For example, if a :class:`~traits.trait_types.Supports` trait requires
599 its values to implement
600 interface ``IPrintable``, and an object is assigned to it which is of
601 class ``Image``, which does not implement ``IPrintable``, then Traits looks for
602 an adapter from ``Image`` to ``IPrintable``, and if one exists the adapter object
603 is assigned to the trait. If necessary, a "chain" of adapter objects might be
604 created, in order to perform the required adaptation.
605
606 Main features
607 `````````````
608
609 The main features of the :mod:`traits.adaptation` package are:
610
611 * Support for Python classes, ABCs, and traits :class:`~.Interface` s
612
613 Protocols can be specified using any of those.
614
615 * Chaining of adapters
616
617 Adapters can be chained, i.e., an object can be adapted
618 to a target protocol as long as there is a sequence of adapters
619 that can be used to transform it.
620
621 * Conditional adaptation
622
623 Adaptation of an object to a protocol can be conditional, i.e. it may
624 succeed or fail depending on the state of the object.
625
626 * Lazy loading
627
628 The classes for the adapter, the origin, and the target protocols can
629 be specified as strings, and are only loaded if they are required.
630
631 Note on terminology
632 ```````````````````
633
634 To avoid confusion, let's define two terms that we will use all the time:
635
636 * We say that a class *provides* a protocol if it is a subclass of the
637 protocol, or if it implements the protocol (if it is an interface)
638
639 * We say that a class *supports* a protocol if it provides the protocol
640 or an adapter object can be built that provides the protocol
641
642 .. index:: adapters; defining
643
644 .. _defining-adapters:
645
646 Defining Adapters
647 `````````````````
648
649 .. index:: Adapter class
650
651 .. _subclassing-adapter:
652
653 The :class:`Adapter` class
654 ::::::::::::::::::::::::::
655
656 The Traits package provides two classes for defining adapters,
657 one for Traits adapters, :class:`~traits.adaptation.adapter.Adapter`,
658 and one for for pure-Python adapters,
659 :class:`~traits.adaptation.adapter.PurePythonAdapter`. These classes
660 streamline the process of creating a new adapter class. They have a standard
661 constructor that does not normally need to be overridden by subclasses. This
662 constructor accepts one parameter, which is the object to be adapted, and
663 assigns that object to an :attr:`adaptee` attribute (a trait in the case
664 of :class:`~traits.adaptation.adapter.Adapter`).
665
666 As an adapter writer, you need to take care of the following:
667
668 * Declare which interfaces the adapter class implements on behalf of the
669 object it is adapting. For example, if we are working with Traits
670 :class:`~.Interface` s, the adapter would be decorated with the
671 :func:`~traits.has_traits.provides` decorator. In the case of Python ABCs,
672 the class would be a subclass of the abstract base class, or be
673 `registered with it
674 <http://docs.python.org/2/library/abc.html#abc.ABCMeta.register>`_.
675
676 * Implement the methods defined in the interfaces declared in the previous
677 step. Usually, these methods are implemented using appropriate members
678 on the adaptee object.
679
680 .. index:: adaptee trait
681
682 * For Traits adapters, define a trait attribute named **adaptee** that
683 declares what type of object it is an adapter for. Usually, this is an
684 :class:`~.Instance` trait.
685
686 .. index::
687 pair: example; Adapter class
688
689 The following code example shows a definition of a simple adapter class::
690
691 from traits.api import Adapter, Instance, provides
692
693 # Declare what interfaces this adapter implements for its client
694 @provides(IName)
695 class PersonToIName(Adapter):
696
697 # Declare the type of client it supports:
698 adaptee = Instance(Person)
699
700 # Implement the 'IName' interface on behalf of its client:
701 def get_name ( self ):
702 name = '{first} {last}'.format(first=self.adaptee.first_name,
703 last=self.adaptee.last_name)
704 return name
705
706 .. index::
707 pair: registering; adapters
708
709 .. _registering-adapters:
710
711 Registering adapters
712 ::::::::::::::::::::
713
714 Once an adapter class has been defined, it has to be registered with the
715 adaptation manager using the :func:`~traits.adaptation.api.register_factory`
716 function.
717
718 The signature of :func:`~traits.adaptation.api.register_factory` is:
719
720 .. currentmodule:: traits.adaptation.api
721 .. function:: register_factory(adapter_class, from_protocol, to_protocol)
722 :noindex:
723
724 The :func:`~traits.adaptation.adaptation_manager.register_factory` function
725 takes as first argument
726 the adapter class (or an :ref:`adapter factory <adapter-factories>`), followed
727 by the protocol to be adapted (the one provided by the adaptee,
728 :attr:`from_protocol`), and the protocol that it provides
729 (:attr:`to_protocol`).
730
731 .. index:: examples; registering adapters
732
733 This is the example from the previous section, were the adapter is registered::
734
735 from traits.adaptation.api import Adapter, Instance, provides
736
737 # Declare what interfaces this adapter implements for its client
738 @provides(IName)
739 class PersonToIName(Adapter):
740
741 # Declare the type of client it supports:
742 adaptee = Instance(Person)
743
744 # Implement the 'IName' interface on behalf of its client:
745 def get_name ( self ):
746 name = '{first} {last}'.format(first=self.adaptee.first_name,
747 last=self.adaptee.last_name)
748 return name
749
750 # ... somewhere else at application startup.
751 register_factory(PersonToIName, Person, IName)
752
753 .. index:: adapters; factory; factories; conditional adaptation
754
755 .. _adapter-factories:
756
757 Adapter factories, and conditional adaptation
758 `````````````````````````````````````````````
759
760 The first argument to the :func:`~traits.adaptation.api.register_factory`
761 function needs not be an adapter *class*, it can be, more generally, an
762 adapter *factory*.
763
764 An adapter factory can be any callable that accepts one positional argument,
765 the adaptee object, and returns an adapter or None if the adaptation was
766 not possible. Adapter factories allow flexibility in the adaptation process,
767 as the result of adaptation may vary depending on the state of the
768 adaptee object.
769
770
771 .. _conditional-adaptation:
772
773 Conditional adaptation
774 ::::::::::::::::::::::
775
776 A common use of adapter factories is to allow adaptation only if the
777 state of the adaptee object allows it. The factory returns an adapter object
778 if adaptation is possible, or None if it is not.
779
780 In the following example, a ``numpy.ndarray`` object can be adapted to provide
781 an ``IImage`` protocol only if the number of dimensions is 2. (For
782 illustration, this example uses Python ABCs rather than Traits Interfaces.)
783 ::
784
785 import abc
786 import numpy
787 from traits.api import Array, HasTraits
788 from traits.adaptation.api import adapt, Adapter, register_factory
789
790 class ImageABC(object):
791 __metaclass__ = abc.ABCMeta
792
793 class NDArrayToImage(Adapter):
794 adaptee = Array
795
796 # Declare that NDArrayToImage implements ImageABC.
797 ImageABC.register(NDArrayToImage)
798
799
800 def ndarray_to_image_abc(adaptee):
801 """ An adapter factory from numpy arrays to the ImageABC protocol."""
802 if adaptee.ndim == 2:
803 return NDArrayToImage(adaptee=adaptee)
804 return None
805
806 # ... somewhere else at application startup
807 register_factory(ndarray_to_image_abc, numpy.ndarray, ImageABC)
808
809 # Try to adapt numpy arrays to images. The `adapt` function is
810 # introduced later in the docs, but you can probably guess what it does ;-)
811
812 # This adaptation fails, as the array is 1D
813 image = adapt(numpy.ndarray([1,2,3]), ImageABC, default=None)
814 assert image == None
815
816 # This succeeds.
817 image = adapt(numpy.array([[1,2],[3,4]]), ImageABC)
818 assert isinstance(image, NDArrayToImage)
819
820 .. index::
821 pair: adapters; requesting
822
823 .. _using-adapters:
824
825 Requesting an adapter
826 `````````````````````
827
828 The ``adapt`` function
829 ::::::::::::::::::::::
830
831 Adapter classes are defined as described in the preceding sections, but you do
832 not explicitly create instances of these classes.
833
834 Instead, the function :func:`~traits.adaptation.adaptation_manager.adapt` is
835 used, giving the object that needs to be adapted and the target protocol.
836
837 For instance, in the example in the :ref:`conditional-adaptation` section,
838 a 2D numpy array is adapted to an ImageABC protocol with
839 ::
840
841 image = adapt(numpy.array([[1,2],[3,4]]), ImageABC)
842
843 In some cases, no single adapter class is registered that adapts the object
844 to the required interface, but a series of adapter classes exist that,
845 together, perform the required adaptation. In such cases, the necessary set
846 of adapter objects are created, and the "last" link in the chain, the one
847 that actually implements the required interface, is returned.
848
849 When a situation like this arises, the adapted object assigned to the trait
850 always contains the smallest set of adapter objects needed to adapt the
851 original object. Also, more specific adapters are preferred over less specific
852 ones. For example, let's suppose we have a class ``Document`` and a subclass
853 ``HTMLDocument``. We register two adapters to an interface ``IPrintable``,
854 ``DocumentToIPrintable`` and ``HTMLDocumentToIPrintable``. The call
855 ::
856
857 html_doc = HTMLDocument()
858 printable = adapt(html_doc, IPrintable)
859
860 will return an instance of the ``HTMLDocumentToIPrintable`` adapter, as it
861 is more specific than ``DocumentToIPrintable``.
862
863 If no single adapter and no adapter chain can be constructed for the requested
864 adaptation, an :class:`~traits.adaptation.adaptation_error.AdaptationError`
865 is raised. Alternatively, one can specify a default value to be returned
866 in this case::
867
868 printable = adapt(unprintable_doc, IPrintable, default=EmptyPrintableDoc())
869
870 Using Traits interfaces
871 :::::::::::::::::::::::
872
873 An alternative syntax to create adapters when using Traits Interfaces is
874 to use the interface class as an adapter factory, for example
875 ::
876
877 printable = IPrintable(html_doc, None)
878
879 is equivalent to
880 ::
881
882 printable = adapt(html_doc, IPrintable, default=None)
883
884 (the default argument, None, is optional).
885
886 Using the ``Supports`` and ``AdaptsTo`` traits
887 ::::::::::::::::::::::::::::::::::::::::::::::
888
889 Using the terminology introduced in this section, we can say that the
890 :class:`~.Instance` trait accepts values that *provide* the specified protocol.
891
892 Traits defines two additional traits that accept values that *support* a
893 given protocol (they provide it or can be adapted to it) instead:
894
895 * The :class:`~.Supports` trait accepts values that support the specified
896 protocol. The value of the trait after assignment is the possibly adapted
897 value (i.e., it is the original assigned value if that provides the protocol,
898 or is an adapter otherwise).
899
900 * The :class:`~.AdaptsTo` trait also accepts values that support the specified
901 protocol. Unlike ``Supports``, ``AdaptsTo`` stores the original, unadapted
902 value.
903
904 If your application works with adaptation, it is natural to use the
905 ``Supports`` trait in place of the ``Instance`` one in most cases. This
906 will allow that application to be extended by adaptation in the future
907 without changing the existing code, without having to invoke adaptation
908 explicitly in your code.
909
910 For example, a Traits object can be written against the ``IPrintable``
911 interface and be open to extensions by adaptation as follows:
912 ::
913
914 from traits.api import (Adapter, HasTraits, Interface, List, provides,
915 register_factory, Str, Supports)
916
917 class IPrintable(Interface):
918 def get_formatted_text(self, n_cols):
919 """ Return text formatted with the given number of columns. """
920
921 class PrintQueue(HasTraits):
922 # This is the key part of the example: we declare a list of
923 # items that provide or can be adapted to IPrintable
924 queue = List(Supports(IPrintable))
925
926 def is_empty(self):
927 return len(self.queue) == 0
928
929 def push(self, printable):
930 self.queue.append(printable)
931
932 def print_next(self):
933 printable = self.queue.pop(0)
934
935 # The elements from the list are guaranteed to provide
936 # IPrintable, so we can call the interface without worrying
937 # about adaptation.
938 lines = printable.get_formatted_text(n_cols=20)
939
940 print('-- Start document --')
941 print('\n'.join(lines))
942 print('-- End of document -\n')
943
944 class TextDocument(HasTraits):
945 """ A text document. """
946 text = Str
947
948 @provides(IPrintable)
949 class TextDocumentToIPrintable(Adapter):
950 """ Adapt TextDocument and provide IPrintable. """
951
952 def get_formatted_text(self, n_cols):
953 import textwrap
954 return textwrap.wrap(self.adaptee.text, n_cols)
955
956
957 # ---- Application starts here.
958
959 # Register the adapter.
960 register_factory(TextDocumentToIPrintable, TextDocument, IPrintable)
961
962 # Create two text documents.
963 doc1 = TextDocument(text='very very long text the will bore you for sure')
964 doc2 = TextDocument(text='once upon a time in a far away galaxy')
965
966 # The text documents can be pushed on the print queue; in the process,
967 # they are automatically adapted by Traits.
968 print_queue = PrintQueue()
969 print_queue.push(doc1)
970 print_queue.push(doc2)
971
972 while not print_queue.is_empty():
973 print_queue.print_next()
974
975 This scripts produces this output:
976 ::
977
978 -- Start document --
979 very very long text
980 the will bore you
981 for sure
982 -- End of document -
983
984 -- Start document --
985 once upon a time in
986 a far away galaxy
987 -- End of document -
988
989
990 Implementation details
991 ``````````````````````
992
993 The algorithm for finding a sequence of adapters adapting an object ``adaptee``
994 to a protocol ``to_protocol`` is based on a weighted graph.
995
996 Nodes on the graphs are protocols (types or interfaces).
997 Edges are adaptation offers that connect a ``offer.from_protocol`` to a
998 ``offer.to_protocol``.
999
1000 Edges connect protocol ``A`` to protocol ``B`` and are weighted by two
1001 numbers in this priority:
1002
1003 1) a unit weight (1) representing the fact that we use 1 adaptation
1004 offer to go from ``A`` to ``B``
1005 2) the number of steps up the type hierarchy that we need to take
1006 to go from ``A`` to ``offer.from_protocol``, so that more specific
1007 adapters are always preferred
1008
1009 The algorithm finds the shortest weighted path between ``adaptee``
1010 and ``to_protocol``. Once a candidate path is found, it tries to
1011 create the chain of adapters using the factories in the adaptation offers
1012 that compose the path. If this fails because of conditional
1013 adaptation (i.e., an adapter factory returns None), the path
1014 is discarded and the algorithm looks for the next shortest path.
1015
1016 Cycles in adaptation are avoided by only considering path were
1017 every adaptation offer is used at most once.
1018
1019 .. _migration:
1020
1021 Migration guide
1022 ```````````````
1023
1024 The implementation of the adaptation mechanism changed in Traits 4.4.0 from
1025 one based on PyProtocols to a new, smaller, and more robust implementation.
1026
1027 Code written against ``traits.protocols`` will not work any longer as the
1028 ``traits.protocols`` API has been removed in Traits 5.0.0 .
1029
1030 This is a list of replacements for the old API:
1031
1032 * :class:`traits.protocols.api.AdaptationFailure`
1033
1034 Use :class:`traits.api.AdaptationError` instead.
1035
1036 * :func:`traits.api.adapts`
1037
1038 Use the :func:`traits.api.register_factory` function.
1039
1040 * :func:`implements`
1041
1042 Use the :func:`traits.api.provides` decorator instead.
1043
1044 * :func:`traits.protocols.api.declareAdapter`
1045
1046 Use the function :func:`traits.api.register_factory`, or the function
1047 :func:`traits.adaptation.api.register_offer` instead. It is no longer
1048 necessary to distinguish between "types", "protocols", and "objects".
1049
1050 * :func:`traits.protocols.api.declareImplementation`
1051
1052 This function
1053 was used occasionally to declare that an arbitrary type (e.g., ``dict``)
1054 implements an interface. Users that use Python ABCs can use the ``register``
1055 method for achieving the same result. Otherwise, use the function
1056 :func:`traits.adaptation.api.register_provides` that declares a "null"
1057 adapter to adapt the type to the interface.
1058
1059 * Testing if a class is an Interface
1060
1061 ``issubclass(klass, Interface)`` is not reliable, use
1062 :func:`traits.api.isinterface` instead
1063
1064 Gotchas
1065 ```````
1066
1067 1) The methods :func:`~traits.adaptation.adaptation_manager.register_factory`,
1068 :func:`~traits.adaptation.adaptation_manager.adapt`,
1069 etc. use a global adaptation manager, which is accessible through the
1070 function
1071 :func:`~traits.adaptation.adaptation_manager.get_global_adaptation_manager`.
1072 The traits automatic adaptation features also use the global manager.
1073 Having a global adaptation manager can get you into trouble, for the usual
1074 reasons related to having a global state. If you want to have more control
1075 over adaptation, we recommend creating a new
1076 :class:`~traits.adaptation.adaptation_manager.AdaptationManager`
1077 instance, use it directly in your application, and set it as the global
1078 manager using
1079 :func:`~traits.adaptation.adaptation_manager.set_global_adaptation_manager`.
1080 A common issue with the global manager arises in unittesting, where adapters
1081 registered in one test influence the outcome of other tests downstream.
1082 Tests relying on adaptation should make sure to reset the state of the
1083 global adapter using
1084 :func:`~traits.adaptation.adaptation_manager.reset_global_adaptation_manager`.
1085
1086 Recommended readings about adaptation
1087 `````````````````````````````````````
1088
1089 This is a list of interesting readings about adaptation and the adapter
1090 pattern outside of Traits:
1091
1092 * `PyProtocols <http://peak.telecommunity.com/protocol_ref/module-protocols.html>`_,
1093 a precursor of ``traits.adaptation``
1094 * `PEP 246 <http://www.python.org/dev/peps/pep-0246/>`_ on object adaptation
1095 * `Article about adapters in Eclipse plugins
1096 <http://www.eclipse.org/articles/article.php?file=Article-Adapters/index.html>`_
1097
1098
1099 .. index:: property traits
1100
1101 .. _property-traits:
1102
1103 Property Traits
1104 ---------------
1105
1106 The predefined Property() trait factory function defines a Traits-based version
1107 of a Python property, with "getter" and "setter" methods. This type of trait
1108 provides a powerful technique for defining trait attributes whose values depend
1109 on the state of other object attributes. In particular, this can be very useful
1110 for creating synthetic trait attributes which are editable or displayable in a
1111 TraitUI view.
1112
1113 .. _property-factory-function:
1114
1115 Property Factory Function
1116 `````````````````````````
1117
1118 The Property() function has the following signature:
1119
1120 .. currentmodule:: traits.traits
1121 .. function:: Property( [fget=None, fset=None, fvalidate=None, force=False, handler=None, trait=None, **metadata] )
1122 :noindex:
1123
1124 All parameters are optional, including the *fget* "getter", *fvalidate*
1125 "validator" and *fset* "setter" methods. If no parameters are specified, then
1126 the trait looks for and uses methods on the same class as the attribute that
1127 the trait is assigned to, with names of the form _get_\ *name*\ (),
1128 _validate_\ *name*\ () and _set_\ *name*\ (), where *name* is the name of the
1129 trait attribute.
1130
1131 If you specify a trait as either the *fget* parameter or the *trait* parameter,
1132 that trait's handler supersedes the *handler* argument, if any. Because the
1133 *fget* parameter accepts either a method or a trait, you can define a Property
1134 trait by simply passing another trait. For example::
1135
1136 source = Property( Code )
1137
1138 This line defines a trait whose value is validated by the Code trait, and whose
1139 getter and setter methods are defined elsewhere on the same class.
1140
1141 If a Property trait has only a getter function, it acts as read-only; if it has
1142 only a setter function, it acts as write-only. It can lack a function due to two
1143 situations:
1144
1145 * A function with the appropriate name is not defined on the class.
1146 * The *force* option is True, (which requires the Property() factory function
1147 to ignore functions on the class) and one of the access functions was not
1148 specified in the arguments.
1149
1150 You can use the **observe** metadata attribute to indicate that the
1151 property depends on the value of another trait. The value of **observe**
1152 follows the same signature as the **expression** parameter in
1153 |HasTraits.observe|, which is also described in the
1154 :ref:`expression section <observe-expression>`. The property will fire a trait
1155 change notification if any of the traits specified by **observe** change. For
1156 example::
1157
1158 class Wheel(Part):
1159 axle = Instance(Axle)
1160 position = Property(observe='axle.chassis.position')
1161
1162 .. index:: property traits; caching value
1163
1164 .. _caching-a-property-value:
1165
1166 Caching a Property Value
1167 ````````````````````````
1168
1169 In some cases, the cost of computing the value of a property trait attribute may
1170 be very high. In such cases, it is a good idea to cache the most recently
1171 computed value, and to return it as the property value without recomputing it.
1172 When a change occurs in one of the attributes on which the cached value depends,
1173 the cache should be cleared, and the property value should be recomputed the
1174 next time its value is requested.
1175
1176 .. index:: cached_property decorator, depends_on metadata
1177
1178 One strategy to accomplish caching would be to use a private attribute for the
1179 cached value, and notification observer methods on the attributes that are
1180 depended on. However, to simplify the situation, Property traits support a
1181 |@cached_property| decorator and **observe** metadata. Use |@cached_property|
1182 to indicate that a getter method's return value should be cached. Use
1183 **observe** to indicate the other attributes that the property depends on.
1184
1185 .. index:: examples; cached property
1186
1187 For example:
1188
1189 .. literalinclude:: /../../examples/tutorials/doc_examples/examples/cached_prop.py
1190 :start-at: from traits.api
1191
1192 The |@cached_property| decorator takes no arguments. Place it on the line
1193 preceding the property's getter method.
1194
1195 As mentioned above, the **observe** metadata attribute accepts extended trait
1196 references. As a result, it can take values that specify attributes on
1197 referenced objects, multiple attributes, or attributes that are selected based
1198 on their metadata attributes.
1199
1200 .. index:: persistence, __getstate__(), __setstate__()
1201
1202 .. _persistence:
1203
1204 Persistence
1205 -----------
1206
1207 In version 3.0, the Traits package provides __getstate__() and __setstate__()
1208 methods on HasTraits, to implement traits-aware policies for serialization and
1209 deserialization (i.e., pickling and unpickling).
1210
1211 .. index:: HasTraits class; pickling, pickling HasTraits objects
1212
1213 .. _pickling-hastraits-objects:
1214
1215 Pickling HasTraits Objects
1216 ``````````````````````````
1217
1218 Often, you may wish to control for a HasTraits subclass which parts of an
1219 instance's state are saved, and which are discarded. A typical approach is to
1220 define a __getstate__() method that copies the object's __dict__ attribute, and
1221 deletes those items that should not be saved. This approach works, but can have
1222 drawbacks, especially related to inheritance.
1223
1224 .. index:: transient; metadata
1225
1226 The HasTraits __getstate__() method uses a more generic approach, which
1227 developers can customize through the use of traits metadata attributes, often
1228 without needing to override or define a __getstate__() method in their
1229 application classes. In particular, the HasTraits __getstate__() method discards
1230 the values of all trait attributes that have the **transient** metadata
1231 attribute set to True, and saves all other trait attributes. So, to mark which
1232 trait values should not be saved, you set **transient** to True in the metadata
1233 for those trait attributes. The benefits of this approach are that you do not
1234 need to override __getstate__(), and that the metadata helps document the
1235 pickling behavior of the class.
1236
1237 .. index:: examples; transient metadata
1238
1239 For example::
1240
1241 # transient_metadata.py -- Example of using 'transient' metadata
1242 from traits.api import HasTraits, File, Any
1243
1244 class DataBase ( HasTraits ):
1245 # The name of the data base file:
1246 file_name = File
1247
1248 # The open file handle used to access the data base:
1249 file = Any( transient = True )
1250
1251 In this example, the DataBase class's file trait is marked as transient because
1252 it normally contains an open file handle used to access a data base. Since file
1253 handles typically cannot be pickled and restored, the file handle should not be
1254 saved as part of the object's persistent state. Normally, the file handle would
1255 be re-opened by application code after the object has been restored from its
1256 persisted state.
1257
1258 .. index:: transient; predefined traits
1259
1260 .. _predefined-transient-traits:
1261
1262 Predefined Transient Traits
1263 ```````````````````````````
1264
1265 A number of the predefined traits in the Traits package are defined with
1266 **transient** set to True, so you do not need to explicitly mark them. The
1267 automatically transient traits are:
1268
1269 * Constant
1270 * Event
1271 * Read-only and write-only Property traits (See :ref:`property-factory-function`)
1272 * Shadow attributes for mapped traits (See :ref:`mapped-traits`)
1273 * Private attributes of HasPrivateTraits subclasses (See :ref:`hasprivatetraits`)
1274 * Delegate traits that do not have a local value overriding the delegation.
1275 Delegate traits with a local value are non-transient, i.e., they are
1276 serialized. (See :ref:`delegatesto`) You can mark a Delegate trait as
1277 transient if you do not want its value to ever be serialized.
1278
1279 .. index:: __getstate__(); overriding
1280
1281 .. _overriding_getstate:
1282
1283 Overriding __getstate__()
1284 `````````````````````````
1285
1286 In general, try to avoid overriding __getstate__() in subclasses of HasTraits.
1287 Instead, mark traits that should not be pickled with ``transient = True``
1288 metadata.
1289
1290 However, in cases where this strategy is insufficient, use the following pattern
1291 to override __getstate__() to remove items that should not be persisted::
1292
1293 def __getstate__ ( self ):
1294 state = super().__getstate__()
1295
1296 for key in [ 'foo', 'bar' ]:
1297 if key in state:
1298 del state[ key ]
1299
1300 return state
1301
1302 .. index:: unpickling HasTraits objects, HasTraits class; unpickling
1303
1304 .. _unpicking-hastraits-objects:
1305
1306 Unpickling HasTraits Objects
1307 ````````````````````````````
1308
1309 The __setstate__() method of HasTraits differs from the default Python behavior
1310 in one important respect: it explicitly sets the value of each attribute using
1311 the values from the state dictionary, rather than simply storing or copying the
1312 entire state dictionary to its **__dict__** attribute. While slower, this
1313 strategy has the advantage of generating trait change notifications for each
1314 attribute. These notifications are important for classes that rely on them to
1315 ensure that their internal object state remains consistent and up to date.
1316
1317 .. note:: If you're manually creating state dictionaries for consumption by
1318 __setstate__(), you should be aware of an additional implementation detail:
1319 when pickling, the HasTraits __getstate__() method returns a dictionary with
1320 an extra ``'__traits_version__'`` key giving the version of Traits used at
1321 pickling time. If this key is not present when unpickling, the HasTraits
1322 __setstate__() method falls back to a compatibility mode and may not restore
1323 the state correctly. For the same reason, if you're overriding
1324 __getstate__(), you should be careful to make the appropriate
1325 ``super().__getstate__()`` call.
1326
1327 .. index:: __setstate__(); overriding
1328
1329 .. _overriding-setstate:
1330
1331 Overriding __setstate__()
1332 `````````````````````````
1333
1334 You may wish to override the HasTraits __setstate__() method, for example for
1335 classes that do not need to receive trait change notifications, and where the
1336 overhead of explicitly setting each attribute is undesirable. You can
1337 override __setstate__() to update the object's __dict__ directly. However, in
1338 such cases, it is important ensure that trait notifications are properly set
1339 up so that later change notifications are handled. You can do this in two ways:
1340
1341 * Call the __setstate__() super method (for example, with an empty state
1342 dictionary).
1343
1344 * Call the HasTraits class's private _init_trait_listeners() method; this
1345 method has no parameters and does not return a result.
1346
1347 .. index:: HasTraits class; methods
1348
1349 .. _useful-methods-on-hastraits:
1350
1351 Useful Methods on HasTraits
1352 ---------------------------
1353
1354 The HasTraits class defines a number of methods, which are available to any
1355 class derived from it, i.e., any class that uses trait attributes. This section
1356 provides examples of a sampling of these methods. Refer to the *Traits API
1357 Reference* for a complete list of HasTraits methods.
1358
1359 .. index:: add_trait()
1360
1361 .. _add-trait:
1362
1363 add_trait()
1364 ```````````
1365
1366 This method adds a trait attribute to an object dynamically, after the object
1367 has been created. For more information, see :ref:`per-object-trait-attributes`.
1368
1369 .. index:: clone_traits()
1370
1371 .. _clone-traits:
1372
1373 clone_traits()
1374 ``````````````
1375
1376 This method copies trait attributes from one object to another. It can copy
1377 specified attributes, all explicitly defined trait attributes, or all explicitly
1378 and implicitly defined trait attributes on the source object.
1379
1380 This method is useful if you want to allow a user to edit a clone of an object,
1381 so that changes are made permanent only when the user commits them. In such a
1382 case, you might clone an object and its trait attributes; allow the user to
1383 modify the clone; and then re-clone only the trait attributes back to the
1384 original object when the user commits changes.
1385
1386 .. index:: trait_set()
1387
1388 .. _trait_set:
1389
1390 trait_set()
1391 ```````````
1392
1393 This method takes a list of keyword-value pairs, and sets the trait attribute
1394 corresponding to each keyword to the matching value. This shorthand is useful
1395 when a number of trait attributes need to be set on an object, or a trait
1396 attribute value needs to be set in a lambda function. For example::
1397
1398 person.trait_set(name='Bill', age=27)
1399
1400 The statement above is equivalent to the following::
1401
1402 person.name = 'Bill'
1403 person.age = 27
1404
1405 .. index:: add_class_trait()
1406
1407 .. _add-class-trait:
1408
1409 add_class_trait()
1410 `````````````````
1411
1412 The add_class_trait() method is a class method, while the preceding HasTraits
1413 methods are instance methods. This method is very similar to the add_trait()
1414 instance method. The difference is that adding a trait attribute by using
1415 add_class_trait() is the same as having declared the trait as part of the class
1416 definition. That is, any trait attribute added using add_class_trait() is
1417 defined in every subsequently-created instance of the class, and in any
1418 subsequently-defined subclasses of the class. In contrast, the add_trait()
1419 method adds the specified trait attribute only to the object instance it is
1420 applied to.
1421
1422 In addition, if the name of the trait attribute ends with a '_', then a new (or
1423 replacement) prefix rule is added to the class definition, just as if the prefix
1424 rule had been specified statically in the class definition. It is not possible
1425 to define new prefix rules using the add_trait() method.
1426
1427 One of the main uses of the add_class_trait() method is to add trait attribute
1428 definitions that could not be defined statically as part of the body of the
1429 class definition. This occurs, for example, when two classes with trait
1430 attributes are being defined and each class has a trait attribute that should
1431 contain a reference to the other. For the class that occurs first in lexical
1432 order, it is not possible to define the trait attribute that references the
1433 other class, since the class it needs to refer to has not yet been defined.
1434
1435 .. index::
1436 pair: examples; add_class_trait()
1437
1438 This is illustrated in the following example::
1439
1440 # circular_definition.py --- Non-working example of mutually-
1441 # referring classes
1442 from traits.api import HasTraits, Trait
1443
1444 class Chicken(HasTraits):
1445 hatched_from = Trait(Egg)
1446
1447 class Egg(HasTraits):
1448 created_by = Trait(Chicken)
1449
1450 As it stands, this example will not run because the **hatched_from** attribute
1451 references the Egg class, which has not yet been defined. Reversing the
1452 definition order of the classes does not fix the problem, because then the
1453 **created_by** trait references the Chicken class, which has not yet been defined.
1454
1455 The problem can be solved using the add_class_trait() method, as shown in the
1456 following code::
1457
1458 # add_class_trait.py --- Example of mutually-referring classes
1459 # using add_class_trait()
1460 from traits.api import HasTraits, Trait
1461
1462 class Chicken(HasTraits):
1463 pass
1464
1465 class Egg(HasTraits):
1466 created_by = Trait(Chicken)
1467
1468 Chicken.add_class_trait('hatched_from', Egg)
1469
1470 .. index:: performance of Traits
1471
1472 .. _performance-considerations-of-traits:
1473
1474 Performance Considerations of Traits
1475 ------------------------------------
1476
1477 Using traits can potentially impose a performance penalty on attribute access
1478 over and above that of normal Python attributes. For the most part, this
1479 penalty, if any, is small, because the core of the Traits package is written in
1480 C, just like the Python interpreter. In fact, for some common cases, subclasses
1481 of HasTraits can actually have the same or better performance than old or new
1482 style Python classes.
1483
1484 However, there are a couple of performance-related factors to keep in mind when
1485 defining classes and attributes using traits:
1486
1487 * Whether a trait attribute defers its value through delegation or prototyping
1488 * The complexity of a trait definition
1489
1490 If a trait attribute does not defer its value, the performance penalty can be
1491 characterized as follows:
1492
1493 * Getting a value: No penalty (i.e., standard Python attribute access speed or
1494 faster)
1495 * Setting a value: Depends upon the complexity of the validation tests
1496 performed by the trait definition. Many of the predefined trait handlers
1497 defined in the Traits package support fast C-level validation. For most of
1498 these, the cost of validation is usually negligible. For other trait
1499 handlers, with Python-level validation methods, the cost can be quite a bit
1500 higher.
1501
1502 If a trait attribute does defer its value, the cases to be considered are:
1503
1504 * Getting the default value: Cost of following the deferral chain. The chain
1505 is resolved at the C level, and is quite fast, but its cost is linear with
1506 the number of deferral links that must be followed to find the default value
1507 for the trait.
1508 * Getting an explicitly assigned value for a prototype: No penalty (i.e.,
1509 standard Python attribute access speed or faster)
1510 * Getting an explicitly assigned value for a delegate: Cost of following the
1511 deferral chain.
1512 * Setting: Cost of following the deferral chain plus the cost of performing
1513 the validation of the new value. The preceding discussions about deferral
1514 chain following and fast versus slow validation apply here as well.
1515
1516 In a typical application scenario, where attributes are read more often than
1517 they are written, and deferral is not used, the impact of using traits is often
1518 minimal, because the only cost occurs when attributes are assigned and
1519 validated.
1520
1521 The worst case scenario occurs when deferral is used heavily, either for
1522 delegation, or for prototyping to provide attributes with default values that
1523 are seldom changed. In this case, the cost of frequently following deferral
1524 chains may impose a measurable performance detriment on the application. Of
1525 course, this is offset by the convenience and flexibility provided by the
1526 deferral model. As with any powerful tool, it is best to understand its
1527 strengths and weaknesses and apply that understanding in determining when use of
1528 the tool is justified and appropriate.
1529
1530 ..
1531 # substitutions
1532
1533 .. |HasTraits.observe| replace:: :func:`~traits.has_traits.HasTraits.observe`
1534 .. |@cached_property| replace:: :func:`~traits.has_traits.cached_property`