Home

Traits 4 User Manual

image

Contents

1. wildcard_rules py Example of trait attribute wildcard rules from traits api import Any HasTraits Int Python class Person HasTraits 34 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 temp_count Int 1 temp_ Any Python In this example the Person class has a temp_count attribute which must be an integer and which has an initial value of 1 Any other attribute with a name starting with temp has an initial value of None and allows any value to be assigned All other object attributes behave like normal Python attributes i e they allow any value to be assigned but they must have a value assigned to them before their first reference Disallow Object The singleton object Disallow can be used with wildcards to disallow all attributes that are not explicitly defined For example disallow py Example of using Disallow with wildcards from traits api import Disallow Float HasTraits Int Str class Person HasTraits name Str age Int weight Float Disallow In this example a Person instance has three trait attributes e name Must be a string its initial value is e age Must be an integer its initial value is 0 e weight Must be a float its initial value is 0 0 All other object attributes are explicitly disallowed That is any attempt to read or set any object attribute other than name age or weight causes an exception
2. Ensures that a trait attribute value is a string that satisfied some additional optional constraints The optional constraints include minimum and maximum lengths and a regular expression that the string must match 88 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 If the value assigned to the trait attribute is a Python numeric type the TraitString handler first coerces the value to a string Values of other non string types result in a TraitError being raised The handler then makes sure that the resulting string is within the specified length range and that it matches the regular expression Example class Person HasTraits name Trait TraitString maxlen 50 regex r A Za z x S This example defines a Person class with a name attribute which must be a string of between 0 and 50 characters that consist of only upper and lower case letters class traits trait_handlers TraitCoerceType aType Ensures that a value assigned to a trait attribute is of a specified Python type or can be coerced to the specified type TraitCoerceType is the underlying handler for the predefined traits and factories for Python simple types The TraitCoerceType class is also an example of a parametrized type because the single TraitCoerceType class allows creating instances that check for totally different sets of values For example class Person HasTraits name Trait TraitCoerc
3. 6 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 traits trait_errors TraitError The weight trait of a Person instance must be a float but a value of 180 lt type str gt was specified gt gt gt bill cweight 180 OK cast to float 180 gt gt gt print bill cweight 180 0 55 gt Other Predefined Traits The Traits package provides a number of other predefined traits besides those for simple types corresponding to other commonly used data types these predefined traits are listed in the following table Refer to the Traits API Reference in the section for the module traits traits for details Most can be used either as simple names which use their built in default values or as callables which can take additional arguments If the trait cannot be used as a simple name it is omitted from the Name column of the table Predefined traits beyond simple types Name Ci Any Al Array Al ArrayOrNone Al Button Bu Callable CArray C Class CI Code Co Color Co CSet C n a Co Dict DictStrAny DictStrBool DictStrFloat DictStrInt DictStrList DictStrLong DictStrStr Di Directory Di Disallow n n a Ei Enum Er Event Es Expression Ex false n File Fi Font Fo Function Fu Generic Ge generic_trait n HTML H Instance In List ListBool ListClass ListComplex List
4. Name of a view element e view element ViewElement View element to associate Returns A view element Description If both name and view_element are specified the view element is associated with name for the current object s class That is view_element is added to the ViewElements object associated with the current object s class indexed by name If only name is specified the function returns the view element object associated with name or None if name has no associated view element View elements retrieved by this function are those that are bound to a class attribute in the class definition or that are associated with a name by a previous call to this method If neither name nor view_element is specified the method returns a View object based on the following order of preference 1 If there is a View object named traits view associated with the current object it is returned 2 If there is exactly one View object associated the current object it is returned 3 Otherwise it returns a View object containing items for all the non event trait attributes on the current object default traits view Returns the name of the default traits view for the object s class classmethod class_default_traits_view Returns the name of the default traits view for the class trait views klass None Returns a list of the names of all view elements associated with the current object s class Parameters klass class
5. Predefined Traits for Simple Types There are two categories of predefined traits corresponding to Python simple types those that coerce values and those that cast values These categories vary in the way that they handle assigned values that do not match the type explicitly defined for the trait However they are similar in terms of the Python types they correspond to and their built in default values as listed in the following table 2 Most callable predefined traits are classes but a few are functions The distinction does not make a difference unless you are trying to extend an existing predefined trait See the Traits API Reference for details on particular traits and see Chapter 5 for details on extending existing traits 1 1 Traits 4 User Manual 5 Traits 4 User Manual Release 4 6 0 dev354 Predefined defaults for simple types Coercing Trait Casting Trait Python Type Built in Default Value Bool CBool Boolean False Complex CComplex Complex number 0 0 Float CFloat Floating point number 0 0 Int Clnt Plain integer 0 Long CLong Long integer OL Str CStr String x Unicode CUnicode Unicode u Trait Type Coercion For trait attributes defined using the predefined coercing traits if a value is assigned to a trait attribute that is not of the type defined for the trait but it can be coerced to the required type then the coerced value is assigned to the att
6. default_value The default value for the trait info text a string A description of the type of value this trait accepts 96 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 validate object name value Validates that a specified value is valid for this trait Note The fast validator version performs this check in C create editor Returns the default traits UI editor for this type of trait class traits trait_types Str default_value lt traits trait_handlers NoDefaultSpecified object gt I metadata Defines a trait whose value must be a Python string using a C level fast validator fast_validate 11 lt type basestring gt The C level fast validator to use class traits trait_types Title default_value lt traits trait_handlers NoDefaultSpecified objects metadata Defines a string type which by default uses the traits ui TitleEditor when used in a View create editor Returns the default traits UI editor to use for a trait class traits trait_types BaseUnicode default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be a Python unicode string default_value u The default value for the trait info text a unicode string A description of the type of value this trait accepts validate object name value Validates that a specified value is valid for this trait
7. Mapped Traits If the Trait function is called with parameters that include one or more dictionaries then the resulting trait is called a mapped trait In practice this means that the resulting object actually contains two attributes e An attribute whose value is a key in the dictionary used to define the trait 28 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 e An attribute containing its corresponding value i e the mapped or shadow value The name of the shadow attribute is simply the base attribute name with an underscore appended Mapped traits can be used to allow a variety of user friendly input values to be mapped to a set of internal program friendly values The following examples illustrates mapped traits that map color names to tuples representing red green blue and transparency values mapped py Example of a mapped trait from traits api import HasTraits Trait standard_color Trait black black 020 00 02 0 1 20 blue 0 0 ui 220 1 0 evan 0 0 1 0 1 0 1 0 green 0 0 1 0 00 Lat magenta 1 0 046 12 6 1 60 orange 0 8 0 196 0 296 1 0 purple 0 69 030 160 160 redr 160 0 0 O40 200 violet 0 31 0194 0 31 107z yellow 1 0 1 0 0 0 1 0 white L0 atl LeO aigh transparent 1 0 2 0 1 0 0 0 9 red_color Trait red standard_color class GraphicShap
8. Note The fast validator version performs this check in C create_editor Returns the default traits UI editor for this type of trait class traits trait_types Unicode default_value lt traits trait_handlers NoDefaultSpecified ob ject gt metadata Defines a trait whose value must be a Python unicode string using a C level fast validator fast_validate 11 type unicode gt None type str gt The C level fast validator to use class traits trait_types BaseBool default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be a Python boolean evaluate The function to use for evaluating strings to this type alias of bool default_value False The default value for the trait info_text a boolean A description of the type of value this trait accepts validate object name value Validates that a specified value is valid for this trait 2 1 API Reference 97 Traits 4 User Manual Release 4 6 0 dev354 Note The fast validator version performs this check in C create editor Returns the default traits UI editor for this type of trait class traits trait_types Bool default_value lt traits trait_handlers NoDefaultSpecified object gt r metadata f Defines a trait whose value must be a Python boolean using a C level fast validator fast_validate 11 type bool gt The C level fast valid
9. Returns the default UI editor for the trait class traits trait_types Tuple types metadata Defines a trait whose value must be a tuple of specified trait types using a C level fast validator init_fast_validator args Set up the C level fast validator class traits trait_types ValidatedTuple types metadata A Tuple trait that supports custom validation __init__ types metadata Returns a ValidatedTuple trait 2 1 API Reference 105 Traits 4 User Manual Release 4 6 0 dev354 Parameters e types zero or more arguments Definition of the default and allowed tuples see BaseTuple for more details e fvalidate callable optional A callable to provide the additional custom validation for the tuple The callable will be passed the tuple value and should return True or False e fvalidate_info string optional A string describing the custom validation to use for the error messages For example value range ValidatedTuple Int 0 Int 1 fvalidate lambda x x 0 lt x 1 This definition will accept only tuples a b containing two integers that satisfy a lt b validate object name value Validates that the value is a valid tuple full_info object name value Returns a description of the trait class traits trait_types List trait None value None minlen 0 maxlen 9223372036854775807 items True metadata Defines a trait whose value must be a list whose it
10. Traits 4 User Manual Release 4 6 0 dev354 Interfaces The Traits package supports declaring and implementing interfaces An interface is an abstract data type that defines a set of attributes and methods that an object must have to work in a given situation The interface says nothing about what the attributes or methods do or how they do it it just says that they have to be there Interfaces in Traits are similar to those in Java They can be used to declare a relationship among classes which have similar behavior but do not have an inheritance relationship Like Traits in general Traits interfaces don t make anything possible that is not already possible in Python but they can make relationships more explicit and enforced Python programmers routinely use implicit informal interfaces what s known as duck typing Traits allows programmers to define explicit and formal interfaces so that programmers reading the code can more easily understand what kinds of objects are actually intended to be used in a given situation Defining an Interface To define an interface create a subclass of Interface from traits api import Interface class IName Interface def get_name self Returns a string which is the name of an object Interface classes serve primarily as documentation of the methods and attributes that the interface defines In this case a class that implements the IName interface must have a method name
11. Traits 4 User Manual Release 4 6 0 dev354 Enthought Inc October 16 2015 Contents 1 User Reference 1 14 Traits4 User Manual 2 245 4 2254 02 68 224548 28482605424 epee het E 1 12 TmdiceSand tables 2 2 x cea ee SERS SST ARD AR ee BS SR ee Ee eee Bee RS 55 2 Developer Reference 57 2 API Reference 2 x4 oe ee ea bbe ee Pee eee beeen eee PEAAS 57 22 Indicesand tables 4i sa dco eta ba i SR ep eee eve MAL cB ig Sh dbp cet BE re So BO R age eee as r n AE gn a eee IE 130 Python Module Index 131 CHAPTER 1 User Reference 1 1 Traits 4 User Manual 1 1 1 Traits 4 User Manual Authors David C Morrill Janet M Swisher Version Document Version 4 Copyright 2005 2006 2008 Enthought Inc All Rights Reserved Redistribution and use of this document in source and derived forms with or without modification are permitted provided that the following conditions are met e Redistributions of source or derived format for example Portable Document Format or Hypertext Markup Language must retain the above copyright notice this list of conditions and the following disclaimer e Neither the name of Enthought Inc nor the names of contributors may be used to endorse or promote products derived from this document without specific prior written permission THIS DOCUMENT IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES INCLUDING BUT NOT LIMITED TO THE
12. full_info object name value Returns a description of the trait create editor Returns the default UI editor for the trait class traits trait_types Range low None high None value None exclude_low False ex clude_high False metadata Defines a trait whose numeric value must be in a specified range using a C level fast validator init_fast_validator args Set up the C level fast validator class traits trait_types BaseEnum args metadata Defines a trait whose value must be one of a specified set of values init_fast_validator args Does nothing for the BaseEnum class Used in the Enum class to set up the fast validator validate object name value Validates that the value is one of the enumerated set of valid values full_info object name value Returns a description of the trait create editor Returns the default UI editor for the trait class traits trait_types Enum args metadata Defines a trait whose value must be one of a specified set of values using a C level fast validator 104 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 init_fast_validator args Set up the C level fast validator class traits trait_types BaseTuple types metadata Defines a trait whose value must be a tuple of specified trait types __init__ types metadata Returns a Tuple trait Parameters types zero or more arguments Definition of the default an
13. get_change_event_collector thread_name Return the dedicated RecordContainer for the thread If no RecordContainer is found for thread_name then a new RecordContainer is created save_to_directory directory_name Save records files into the directory Each RecordContainer will dump its records on a separate file named lt thread_name gt trace class traits util event_tracer ChangeEventRecorder container A single thread trait change event recorder pre_tracer obj name old new handler Record a string representation of the trait change dispatch post_tracer obj name old new handler exception None Record a string representation of the trait change return class traits util event_tracer MultiThreadChangeEventRecorder container A thread aware trait change recorder The class manages multiple ChangeEventRecorders which record trait change events for each thread in a sepa rate file close Close and stop all logging pre_tracer obj name old new handler The traits pre event tracer This method should be set as the global pre event tracer for traits 2 1 API Reference 129 Traits 4 User Manual Release 4 6 0 dev354 post_tracer obj name old new handler exception None The traits post event tracer This method should be set as the global post event tracer for traits traits util event_tracer record_events args kwds Multi threaded trait change event tracer Usage gt gt
14. line 12 in _constant_changed raise ValueError ValueError Notice that this traceback has information about where we changed constant Note This is a toy example use Constant from traits api if you actually want a constant trait Tracing Traits Change Events Occasionally it is necessary to find the chain of event dispatches in traits classes To help with debugging a record events context manager is provided in mod traits util event_tracer Trait change events taking place inside the context block will be recorded in a change event container see example below and can be saved to files a file for each thread for further inspection Example from traits api import x from traits util event_tracer import record_events class MyModel HasTraits number Float 2 0 list_of_numbers List Float count Int 0 on_trait_change number def _add_number_to_list self value self list_of_numbers append value on_trait_change list_of_numbers def count items self self count len self list on numbers def add_to_number self value self number value my_model MyModel with record_events as change_event_container my_model number 4 7 my_model number 3 save files locally change_event_container save_to_directory 54 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 Running the above example will write a file named MAinThrea
15. provides IName class PersonToIName Adapter Declare the type of client it supports adaptee Instance Person Implement the IName interface on behalf of its client def get_name self name first last format first self adaptee first_name last self adaptee last_name return name Registering adapters Once an adapter class has been defined it has to be registered with the adaptation manager using the register factory function The signature of register factory is traits adaptation api register_factory adapter_class from_protocol to_protocol The register_factory function takes as first argument the adapter class or an adapter factory followed by the protocol to be adapted the one provided by the adaptee from_protocol and the protocol that it provides to_protocol This is the example from the previous section were the adapter is registered 40 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 from traits adaptation api import Adapter Instance provides Declare what interfaces this adapter implements for its client provides IName class PersonToIName Adapter Declare the type of client it supports adaptee Instance Person Implement the IName interface on behalf of its client def get_name self name first last format first self adaptee first_name last self adaptee last_name return name somewhere e
16. traits trait_numeric CArray dtype None shape None value None typecode None object gt ob Defines a trait whose value can be anything and whose definition can be redefined via assignment using a Trait Value object 94 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 metadata trait_value True The standard metadata for the trait class traits trait_types BaseInt default_value lt traits trait_handlers NoDefaultSpecified ob ject gt metadata Defines a trait whose type must be an int or long evaluate The function to use for evaluating strings to this type alias of int default_value 0 The default value for the trait info text an integer int or long A description of the type of value this trait accepts validate object name value Validates that a specified value is valid for this trait create editor Returns the default traits UI editor for this type of trait class traits trait_types Int default_value lt traits trait_handlers NoDefaultSpecified object gt netadata Defines a trait whose type must be an int or long using a C level fast validator fast_validate 20 The C level fast validator to use class traits trait_types BaseLong default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be a Python long evaluate The function to use for evaluating strings to this
17. Start document very very long text the will bore you for sure End of document Start document once upon a time in a far away galaxy End of document Implementation details The algorithm for finding a sequence of adapters adapting an object adaptee to a protocol to_protocol is based on a weighted graph Nodes on the graphs are protocols types or interfaces Edges are adaptation offers that connect a offer from_protocol toaoffer to_protocol Edges connect protocol A to protocol B and are weighted by two numbers in this priority 1 a unit weight 1 representing the fact that we use 1 adaptation offer to go from A to B 2 the number of steps up the type hierarchy that we need to take to go from A to offer from_protocol so that more specific adapters are always preferred The algorithm finds the shortest weighted path between adaptee and to_protocol Once a candidate path is found it tries to create the chain of adapters using the factories in the adaptation offers that compose the path If this fails because of conditional adaptation i e an adapter factory returns None the path is discarded and the algorithm looks for the next shortest path Cycles in adaptation are avoided by only considering path were every adaptation offer is used at most once 44 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 Migration guide The implementation of the adaptation
18. Trait class class MyClass pass foo Trait MyClass Values must be instances of class or of a subclass of class The default value is None but None cannot be assigned as a value Trait None class class MyClass Similar to the previous format but None can be assigned as a value pass foo Trait None MyClass Trait instance Values must be instances of the class MyClass same class as instance or of a sub pass class of that class The specified in i MyClass stance is the default value foo Trait i Trait handler Trait TraitEnum Assignment to this trait is vali dated by an object derived from traits TraitHandler Trait default type constant dict class function handler trait Trait 0 0 0 0 stuff TupleType This is the most general form of the function The notation means a list of one or more of any of the items listed between the braces Thus the most general form of the function consists of a default value followed by one or more of several possible items A trait defined by multiple items is called a compound trait 2 1 API Reference 59 Traits 4 User Manual Release 4 6 0 dev354 All forms of the Trait function accept both predefined and arbitrary keyword arguments The value of each keyword argument becomes bound to the resulting trait object as the value of an attribute having the same na
19. TraitDict class in traits trait_handlers 93 TraitDictEvent class in traits trait_handlers 93 TraitDictObject class in traits trait_handlers 93 TraitDocumenter class in traits util trait_documenter 127 TraitEnum class in traits trait_handlers 90 TraitError class in traits trait_errors 84 TraitExpression class in traits trait_handlers 92 TraitFactory class in traits traits 58 TraitFunction class in traits trait_handlers 90 TraitHandler class in traits trait_handlers 88 TraitHandler class 30 TraitImportError class in traits traits 58 TraitInstance class in traits trait_handlers 90 TraitList class in traits trait_handlers 92 TraitListEvent class in traits trait_handlers 92 TraitListObject class in traits trait_handlers 93 TraitMap class in traits trait_handlers 91 TraitNotificationError class in traits trait_errors 84 TraitPrefixList class in traits trait_handlers 90 TraitPrefixList class 30 examples 30 TraitPrefixMap class in traits trait_handlers 91 TraitPrefixMap class 30 examples 31 class TraitRange class in traits trait_handlers 88 traits traits has_traits HasTraits method 77 traits adaptation module 116 traits adaptation adaptation_error module 116 traits adaptation adaptation_manager module 117 traits adaptation adaptation_offer module 118 traits adaptation adapter module 119 traits adaptation cached_adapter_factory module 119
20. as arguments to the Trait function class traits trait_handlers TraitEnum values Ensures that a value assigned to a trait attribute is a member of a specified list of values TraitEnum is the underlying handler for the forms of the Trait function that take a list of possible values 90 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 class traits trait_handlers TraitPrefixList values Ensures that a value assigned to a trait attribute is a member of a list of specified string values or is a unique prefix of one of those values TraitPrefixList is a variation on TraitEnum The values that can be assigned to a trait attribute defined using a TraitPrefixList handler is the set of all strings supplied to the TraitPrefixList constructor as well as any unique prefix of those strings That is if the set of strings supplied to the constructor is described by s1 so Sn then the string v is a valid value for the trait if v sj for one and only one pair of values i j If v is a valid value then the actual value assigned to the trait attribute is the corresponding si value that v matched Example class Person HasTraits married Trait no TraitPrefixList yes no class The Person class has a married trait that accepts any of the strings y ye yes n or no as valid values However the actual values assigned as the value of
21. check whether the trait attributes that _name_fired handlers are applied to are actually events The function names are simply synonyms for programmer convenience Similarly a function named on_trait_event can be used as a synonym for on_trait_change for dynamic notification 20 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 Undefined Object Python defines a special singleton object called None The Traits package introduces an additional special singleton object called Undefined The Undefined object is used to indicate that a trait attribute has not yet had a value set i e its value is undefined Undefined is used instead of None because None is often used for other meanings such as that the value is not used In particular when a trait attribute is first assigned a value and its associated trait notification handlers are called Undefined is passed as the value of the old parameter to each handler to indicate that the attribute previously had no value Similarly the value of a trait event is always Undefined 1 1 5 Deferring Trait Definitions One of the advanced capabilities of the Traits package is its support for trait attributes to defer their definition and value to another object than the one the attribute is defined on This has many applications especially in cases where objects are logically contained within other objects and may wish to inherit or derive some attributes from the ob
22. class traits trait_handlers TraitList trait None minlen 0 maxlen 9223372036854775807 has_items True Ensures that a value assigned to a trait attribute is a list containing elements of a specified type and that the length of the list is also within a specified range TraitList also makes sure that any changes made to the list after it is assigned to the trait attribute do not violate the list s type and length constraints TraitList is the underlying handler for the predefined list based traits Example 92 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 class Card Has class Hand Has1 pass raits raits cards Trait TraitList Trait Card maxlen 52 This example defines a Hand class which has a cards trait attribute which is a list of Card objects and can have from 0 to 52 items in the list class traits trait_handlers TraitListObject trait object name value class traits trait_handlers TraitSetEvent removed None added None class traits trait_handlers TraitSetObject trait object name value copy Return a true set object with a copy of the data class traits trait_handlers TraitDictEvent added None changed None removed None class traits trait_handlers TraitDict key_trait None value_trait None has_items True Ensures that values assigned to a trait attribute are dictionaries whose keys and values are of specified t
23. class traits traits ForwardProperty metadata validate None handler None Used to implement Property traits where accessor functions are defined implicitly on the class traits traits Color traits traits RGBColor traits traits Font Functions traits traits Trait value_type metadata Creates a trait definition This function accepts a variety of forms of parameter lists 58 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 Format Example Description Trait default Trait 150 0 The type of the trait is inferred from the type of the default value which must be in ConstantTypes Trait default other1 other2 Trait None 0 1 2 many The trait accepts any of the enumer ated values with the first value be ing the default value The values must be of types in ConstantTypes but they need not be of the same type The default value is not valid for assignment unless it is repeated later in the list Trait default other1 other2 Trait None 0 1 2 many Similar to the previous format but takes an explicit list or a list vari able Trait type Trait Int The type parameter must be a name of a Python type see PythonTypes Assigned values must be of exactly the specified type no casting or co ercion is performed The default value is the appropriate form of zero False or emtpy string set or sequence
24. listener_deleted ref 114 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 trait _notifiers Module Classes that implement and support the Traits change notification mechanism Classes class traits class traits class traits class traits class traits trait_noti strait noti trait_noti trait roti trait_noti Dynamic change notify wrapper fiers fiers fiers fiers fiers NotificationExceptionHandlerState handler reraise_exceptions locked NotificationExceptionHandler StaticAnyTraitChangeNotifyWrapper handler StaticTraitChangeNotifyWrapper handler TraitChangeNotifyWrapper handler owner target None This class is in charge to dispatch trait change events to dynamic listener typically created using the on_trait_change method or the decorator with the same name dispatch handler args Dispatch the event to the listener This method is normally the only one that needs to be overridden in a subclass to implement the subclass s dispatch mechanism class traits trait_notifiers ExtendedTraitChangeNotifyWrapper handler owner tar get None Change notify wrapper for extended trait change events The extended notifiers are set up internally when using extended traits to add remove traits listeners when one of the intermediate traits changes For example in a listener for the extended trait a b we need to add remove listeners
25. A class such that all returned names must correspond to instances of this class Possible values include e Group e Item e View e ViewElement ViewSubElement Description If klass is specified the list of names is filtered such that only objects that are instances of the specified class are returned trait_view_elements Returns the ViewElements object associated with the object s class The returned object can be used to access all the view elements associated with the class 68 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 classmethod class_trait_view_elements Returns the ViewElements object associated with the class The returned object can be used to access all the view elements associated with the class configure traits filename None view None kind None edit True context None han dler None id scrollable None args Creates and displays a dialog box for editing values of trait attributes as if it were a complete self contained GUI application Parameters filename str The name including path of a file that contains a pickled representa tion of the current object When this parameter is specified the method reads the corre sponding file if it exists to restore the saved values of the object s traits before displaying them If the user confirms the dialog box by clicking OK the new values are written to the file If this parameter is not
26. Eclipse plugins Property Traits The predefined Property trait factory function defines a Traits based version of a Python property with getter and setter methods This type of trait provides a powerful technique for defining trait attributes whose values depend on the state of other object attributes In particular this can be very useful for creating synthetic trait attributes which are editable or displayable in a TraitUI view Property Factory Function The Property function has the following signature traits adaptation api Property feet None fset None fvalidate None force False han dler None trait None metadata J All parameters are optional including the fget getter fvalidate validator and fset setter methods If no parame ters are specified then the trait looks for and uses methods on the same class as the attribute that the trait is assigned to with names of the form _get_name _validate_name and _set_name where name is the name of the trait attribute If you specify a trait as either the fget parameter or the trait parameter that trait s handler supersedes the handler argument if any Because the fget parameter accepts either a method or a trait you can define a Property trait by simply passing another trait For example source Property Code This line defines a trait whose value is validated by the Code trait and whose getter and setter methods are de
27. HasTraits Base class for adapters with traits traits adaptation adapter adapts from_ to extra None factory None cached False when A class advisor for declaring adapters Parameters e from_ type or interface What the adapter adapts from or a list of such types or interfaces the _ suffix is used because from is a Python keyword e to type or interface What the adapter adapts fo or a list of such types or interfaces e factory callable An optional factory for actually creating the adapters This is any callable that takes a single argument which is the object to be adapted The factory should return an adapter if it can perform the adaptation and None if it cannot e cached bool Should the adapters be cached If an adapter is cached then the factory will produce at most one adapter per instance e when str A Python expression that selects which instances of a particular type can be adapted by this factory The expression is evaluated in a namespace that contains a single name adaptee which is bound to the object to be adapted e g adaptee is folder Note The cached and when arguments are ignored if factory is specified cached_adapter_factory Module An adapter factory that caches adapters per instance class traits adaptation cached_adapter_factory CachedAdapterFactory Bases traits has_traits HasTraits An adapter factory that caches adapters per instan
28. HasTraits Subclasses Because the HasTraits class implicitly contains the attribute definition _ Python sub classes of HasTraits by default have very standard Python attribute behavior for any attribute not explicitly defined as a trait attribute However the wildcard trait attribute definition rules make it easy to create subclasses of HasTraits with very non standard attribute behavior Two such subclasses are predefined in the Traits package HasStrictTraits and HasPrivateTraits HasStrictTraits This class guarantees that accessing any object attribute that does not have an explicit or wildcard trait definition results in an exception This can be useful in cases where a more rigorous software engineering approach is employed than is typical for Python programs It also helps prevent typos and spelling mistakes in attribute names from going unnoticed a misspelled attribute name typically causes an exception The definition of HasStrictTraits is the following class HasStrictTraits HasTraits _ Disallow HasStrictTraits can be used to create type checked data structures as in the following example class TreeNode HasStrictTraits left This right This value Str This example defines a TreeNode class that has three attributes left right and value The left and right attributes can only be references to other instances of TreeNode or subclasses while the value attribute must be a string 1 1 Traits 4 U
29. IMPLIED WAR RANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT IN DIRECT INCIDENTAL SPECIAL EXEMPLARY OR CONSEQUENTIAL DAMAGES INCLUDING BUT NOT LIMITED TO PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES LOSS OF USE DATA OR PROFITS OR BUSINESS INTERRUPTION HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY WHETHER IN CONTRACT STRICT LIABILITY OR TORT INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS DOCUMENT EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE All trademarks and registered trademarks are the property of their respective owners Enthought Inc 515 Congress Avenue Suite 2100 Austin TX 78701 1 512 536 1057 voice 1 512 536 1059 fax http www enthought com info enthought com Traits 4 User Manual Release 4 6 0 dev354 1 1 2 Introduction The Traits package for the Python language allows Python programmers to use a special kind of type definition called a trait This document introduces the concepts behind and usage of the Traits package For more information on the Traits package refer to the Traits web page This page contains links to downloadable packages the source code repository and the Traits development website Additional documentation for the Traits package is available from the Traits web page including e Traits API Reference e TraitsUI User Manual
30. None module None metadata A traits whose value must support a specified protocol In other words the value of the trait directly provide or can be adapted to the given protocol Interface or type The value of the trait after assignment is the possibly adapted value i e it is the original assigned value if that provides the protocol or is an adapter otherwise The original unadapted value is stored in a shadow attribute with the same name followed by an underscore e g foo and foo_ post_setattr object name value Performs additional post assignment processing as_ctrait Returns a CTrait corresponding to the trait defined by this class class traits trait_types AdaptsTo klass None factory None args None kw None al low_none True adapt None module None metadata A traits whose value must support a specified protocol In other words the value of the trait directly provide or can be adapted to the given protocol Interface or type The value of the trait after assignment is the original unadapted value A possibly adapted value is stored in a shadow attribute with the same name followed by an underscore e g foo and foo_ class traits trait_types Type value None klass None allow_none True metadata Defines a trait whose value must be a subclass of a specified class validate object name value Validates that the value is a valid object instance resolve object name
31. a camel case string into words separated by spaces For example gt gt gt camel case to words CamelCase Camel Case clean strings Module Provides functions that mange strings to avoid characters that would be problematic in certain situations traits util clean_strings clean_filename name Munge a string to avoid characters that might be problematic as a filename in some filesystems traits util clean_strings clean_timestamp dt None microseconds False Return a timestamp that has been cleansed of characters that might cause problems in filenames namely colons If no datetime object is provided then uses the current time Description The timestamp is in ISO 8601 format with the following exceptions gt Colons are replaced by underscores _ Microseconds are not displayed if the microseconds parameter is False Parameters e dt None or datetime datetime If None then the current time is used e microseconds bool Display microseconds or not Returns A string timestamp traits util clean_strings python_name name Attempt to make a valid Python identifier out of a name deprecated Module A decorator for marking methods functions as deprecated traits util deprecated deprecated message A factory for decorators for marking methods functions as deprecated home_directory Module traits util home_directory get_home_directory Determine the user s home
32. always possible Writing a static change notification handler requires that for a class whose trait attribute changes you are interested in you write a method on that class or a subclass Therefore you must know in advance what classes and attributes you want notification for and you must be the author of those classes Static notification also entails that every instance of the class has the same notification handlers To indicate that a particular method is a static notification handler for a particular trait you have two options e Apply the on_trait_change decorator to the method e Give the method a special name based on the name of the trait attribute it listens to Handler Decorator The most flexible method of statically specifying that a method is a notification handler for a trait is to use the on_trait_change decorator The on_trait_change decorator is more flexible than specially named method han dlers because it supports the very powerful extended trait name syntax see The name Parameter You can use the decorator to set handlers on multiple attributes at once on trait attributes of linked objects and on attributes that are selected based on trait metadata Decorator Syntax The syntax for the decorator is extended_trait_name self Pe on_trait_change def any_method_name 1 1 Traits 4 User Manual 17 Traits 4 User Manual Release 4 6 0 dev354 In this case extended_t
33. as the keyword Internal Metadata Attributes The following metadata attributes are used internally by the Traits package and can be queried e array Indicates whether the trait is an array e default Returns the default value for the trait if known otherwise it returns Undefined e default_kind Returns a string describing the type of value returned by the default attribute for the trait The possible values are value The default attribute returns the actual default value list A copy of the list default value dict A copy of the dictionary default value self The default value is the object the trait is bound to the default attribute returns Undefined factory The default value is created by calling a factory the default attribute returns Undefined method The default value is created by calling a method on the object the trait is bound to the default attribute returns Undefined e delegate The name of the attribute on this object that references the object that this object delegates to e inner_traits Returns a tuple containing the inner traits for the trait For most traits this is empty but for List and Dict traits it contains the traits that define the items in the list or the keys and values in the dictionary e parent The trait from which this one is derived e prefix A prefix or substitution applied to the delegate attribute See Deferring Trait Definitions for details e trait t
34. attributes This class is an alternative to trait validator functions A trait handler has several advantages over a trait validator function due to being an object Trait handlers have constructors and state Therefore you can use them to create parametrized types Trait handlers can have multiple methods whereas validator functions can have only one callable interface This feature allows more flexibility in their implementation and allows them to handle a wider range of cases such as interactions with other components error object name value Raises a TraitError exception Parameters e object object The object whose attribute is being assigned e name str The name of the attribute being assigned e value object The proposed new value for the attribute Description This method is called by the validate method when an assigned value is not valid Raising a TraitError exception either notifies the user of the problem or in the case of compound traits provides a chance for another trait handler to handle to validate the value 84 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 full_info object name value Returns a string describing the type of value accepted by the trait handler Parameters e object object The object whose attribute is being assigned e name str The name of the attribute being assigned e value The proposed new value for the at
35. default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be an instance of a simple Python type validate object name value Validates that the value is a Python callable class traits trait_types This value None allow_none True metadata Defines a trait whose value must be an instance of the defining class info_text an instance of the same type as the receiver A description of the type of value this trait accepts fast_validate 2 The C level fast validator to use class traits trait_types self value None allow_none True metadata Defines a trait whose value must be an instance of the defining class and whose default value is the object containing the trait default_value_type 2 The default value type to use i e self class traits trait_types Function default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be a Python function 2 1 API Reference 101 Traits 4 User Manual Release 4 6 0 dev354 fast_validate 11 lt type function gt The C level fast validator to use info_text a function A description of the type of value this trait accepts class traits trait_types Method default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be a Python method fast_validate 11
36. defined at the time that the manager attribute is defined Handling this common design pattern is the main reason for providing the This trait Note that if a trait attribute is defined using This on one class and is referenced on an instance of a subclass the This trait verifies values based on the class on which it was defined For example gt gt gt from traits api import HasTraits This gt gt gt class Employee HasTraits manager This gt gt gt class Executive Employee 3 Available in Python 2 5 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 pass gt gt gt fred Employee gt gt gt mary Executive gt gt gt The following is OK because fred s manager can be an gt gt gt instance of Employee or any subclass gt gt gt fred manager mary gt gt gt This is also OK because mary s manager can be an Employee gt gt gt mary manager fred List of Possible Values You can define a trait whose possible values include disparate types To do this use the predefined Enum trait and pass it a list of all possible values The values must all be of simple Python data types such as strings integers and floats but they do not have to be all of the same type This list of values can be a typical parameter list an explicit bracketed list or a variable whose type is list The first item in the list is used as the default value
37. directory 2 1 API Reference 125 Traits 4 User Manual Release 4 6 0 dev354 resource Module Utility functions for managing and finding resources ie images files etc get_path Returns the absolute path of a class or instance create_unique_name Creates a name with a given prefix that is not in a given list of existing names The separator between the prefix and the rest of the name can also be specified default is a find_resource Given a setuptools project specification string MyProject gt 2 1 and a partial path leading from the projects base directory to the desired resource will return either an opened file object or if specified a full path to the resource traits util resource get_path path Returns an absolute path for the specified path path can be a string class or instance traits util resource create_unique_name prefix names separator _ Creates a name starting with prefix that is not in names traits util resource find_resource project resource_path alt_path None re turn_path False Returns a file object or file path pointing to the desired resource Parameters e project str The name of the project to look for the resource in Can be the name or a requirement string Ex MyProject MyProject gt 1 0 MyProject 1 1 e resource_path str The path to the file from inside the package If the file desired is M
38. e Traits Technical Notes What Are Traits A trait is a type definition that can be used for normal Python object attributes giving the attributes some additional characteristics e Initialization A trait has a default value which is automatically set as the initial value of an attribute before its first use in a program e Validation A trait attribute is explicitly typed The type of a trait based attribute is evident in the code and only values that meet a programmer specified set of criteria i e the trait definition can be assigned to that attribute Note that the default value need not meet the criteria defined for assignment of values Traits 4 0 also supports defining and using abstract interfaces as well as adapters between interfaces e Deferral The value of a trait attribute can be contained either in the defining object or in another object that is deferred to by the trait e Notification Setting the value of a trait attribute can notify other parts of the program that the value has changed e Visualization User interfaces that allow a user to interactively modify the values of trait attributes can be automatically constructed using the traits definitions This feature requires that a supported GUI toolkit be installed However if this feature is not used the Traits package does not otherwise require GUI support For details on the visualization features of Traits see the TraitsUI User Manual A class can freely m
39. gt from trace_recorder import record_events gt gt gt with record_events as change_event_container ei my_model some_trait True gt gt gt change_event_container save_to_directory C dev trace This will install a tracer that will record all events that occur from setting of some_trait on the my_model instance The results will be stored in one file per running thread in the directory C devtrace The files are named after the thread being traced 2 2 Indices and tables e genindex e search e search 130 Chapter 2 Developer Reference Python Module Index t traits traits traits traits traits traits traits traits traits traits traits traits traits traits traits traits traits traits traits traits traits traits traits traits traits traits traits traits traits traits traits adaptation adaptation adaptation 117 adaptation adaptation adaptation 119 adapter 61 category 6l etsconfig 120 etsconfig e has_dynamic interface_c has_traits 62 traits util L toposort 127 116 traits util trait_documenter 127 adaptation_error 116 adaptation_manager adaptation_offer 118 adapter 119 cached_adapter_factory tsconfig 120 _views 80 hecker 82 protocols 120 testing 120 testing doc testing nos testing uni trait_error trait_handl trait_notif trait_numer trait_types trai
40. gt gt gt from traits api import Enum HasTraits List gt gt gt class InventorylItem HasTraits possible stock states List None 0 1 2 3 many stock Enum 0 values possible_stock_states Enumerated list default value is 0 The list of allowed values is whatever possible_stock_states holds gt gt gt hats InventoryItem 1 1 Traits 4 User Manual 9 Traits 4 User Manual Release 4 6 0 dev354 gt gt gt hats stock 0 gt gt gt hats stock 2 OK gt gt gt hats stock 4 TraitError like above Traceback most recent call last traits trait_errors TraitError The stock trait of an InventoryItem instance must be None or 0 or 1 or 2 or 3 or many but a value of 4 lt type int gt was specified gt gt gt hats possible_stock_states append 4 Add 4 to list of allowed values gt gt gt hats stock 4 OK Trait Metadata Trait objects can contain metadata attributes which fall into three categories e Internal attributes which you can query but not set e Recognized attributes which you can set to determine the behavior of the trait e Arbitrary attributes which you can use for your own purposes You can specify values for recognized or arbitrary metadata attributes by passing them as keyword arguments to callable traits The value of each keyword argument becomes bound to the resulting trait object as the value of an attribute having the same name
41. gt gt gt odd_stuff very_odd 0 Traceback most recent call last File test py line 25 in odd_stuff very_odd 0 File C wrk srce lib enthought traits traits py line 1119 in validate raise TraitError excp traits traits TraitError The very_odd trait of an AnOddClass instance must be a positive odd integerx or 10 lt an integer lt 1 but a value of 0 lt type int gt was specified Note the emphasized result returned by the info method which is embedded in the exception generated by the invalid assignment 1 1 7 Advanced Topics The preceding sections provide enough information for you to use traits for manifestly typed attributes with initial ization and validation This section describes the advanced features of the Traits package Initialization and Validation Revisited The following sections present advanced topics related to the initialization and validation features of the Traits package e Dynamic initialization e Overriding default values e Reusing trait definitions e Trait attribute definition strategies Dynamic Initialization When you define trait attributes using predefined traits the Trait factory function or trait handlers you typically specify their default values statically You can also define a method that dynamically initializes a trait attribute the first time that the attribute value is accessed To do this you define a method on the same class as the trait attribute w
42. interface editor supports rollover tips then the first_name field would display first or personal name when the user moves the mouse over it the last_name field would display last or family name when moused over To get the value of a trait metadata attribute you can use the trait method on a HasTraits object to get a reference to a specific trait and then access the metadata attribute metadata py Example of accessing trait metadata attributes from traits api import HasTraits Int List Float Instance Any TraitType class Foo HasTraits pass class Test HasTraits i Int 99 lf List Float foo Instance Foo any Any 1 2 3 t Test print t trait i default 99 print t trait i default_kind value print t trait i inner_traits print t trait i is_trait_type Int True print t trait i is_trait_type Float False print t trait lf default print t trait lf default_kind list print t trait lf inner_traits lt traits traits CTrait object at 0x01B24138 gt print t trait lf is_trait_type List True print t trait lf is_trait_type TraitType True print t trait lf is_trait_type Float False print t trait lf inner_traits 0 is_trait_type Float True print t trait foo default lt undefined gt print t trait foo default_kind factory print t trait foo inner_trait
43. last_name Cooper gt gt gt sally last_name sally mother ERR string expected Traceback most recent call last File lt stdin gt line 1 in File c srce trunk enthought traits trait_handlers py line 163 in error raise TraitError object name self info value traits trait_errors Traiterroer The last_name trait of a Parent instance must be a string but a value of lt __main__ Parent object at Ox014D6D80 gt lt class __main__ Parent gt was specified non A Child object delegates its last_name attribute value to its father object s last_name attribute Because the prefix parameter was not specified in the DelegatesTo initializer the attribute name on the delegatee is the same as the original attribute name Thus the last_name of a Child is the same as the last_name of its father When either the last_name of the Child or the last_name of the father is changed both attributes reflect the new value PrototypedFrom class PrototypedFrom prototype prefix listenable True metadata The prototype parameter is a string that specifies the name of an attribute on the same object which refers to the object whose attribute is prototyped it is usually an Instance trait The prototyped attribute behaves similarly to a delegated attribute until it is explicitly changed from that point forward the prototyped attribute changes independently from its prototype The prefix and listenable parame
44. mechanism changed in Traits 4 4 0 from one based on PyProtocols to a new smaller and more robust implementation Code written against traits protocols will continue to work although the traits protocols API has been dep recated and its members will log a warning the first time they are accessed The traits protocols package will be removed in Traits 5 0 This is a list of replacements for the old API traits protocols api AdaptationFailure Use traits api AdaptationError instead traits api adapts Use the traits api register_factory function fa mplements Use the traits api provides decorator instead traits protocols api declareAdapter Use the function traits api register_factory or the function traits adaptation api register_offer instead It is no longer necessary to distinguish 39 66 between types protocols and objects traits protocols api declareImplementation This function was used occasionally to declare that an arbitrary type e g dict implements an interface Users that use Python ABCs can use the register method for achieving the same result Otherwise use the function traits adaptation api register_provides that declares a null adapter to adapt the type to the interface Testing if a class is an Interface issubclass klass Interface isnot reliable use traits api isinterface instead Gotchas 1 The adaptation mechanism do
45. must be the name of a file using a C level fast validator 2 1 API Reference 103 Traits 4 User Manual Release 4 6 0 dev354 class traits trait_types BaseDirectory value auto_set False entries 0 exists False metadata Defines a trait whose value must be the name of a directory info text a directory name A description of the type of value this trait accepts validate object name value Validates that a specified value is valid for this trait Note The fast validator version performs this check in C classtraits trait types Directory value auto_set False entries 0 exists False meta data Defines a trait whose value must be the name of a directory using a C level fast validator class traits trait_types BaseRange Jow None high None value None exclude_low False ex clude_high False metadata Defines a trait whose numeric value must be in a specified range init_fast_validator args Does nothing for the BaseRange class Used in the Range class to set up the fast validator validate object name value Validate that the value is in the specified range float_validate object name value Validate that the value is a float value in the specified range int_validate object name value Validate that the value is an int value in the specified range long_validate object name value Validate that the value is a long value in the specified range
46. not need to call the TraitHandler base class s constructor The only method that a custom trait handler must implement is validate Refer to the Traits API Reference for details about this function Example Custom Trait Handler The following example defines the OddInt trait also implemented as a trait type in Defining a Trait Type using a TraitHandler subclass custom_traithandler py Example of a custom TraitHandler import types from traits api import TraitHandler class TraitOddInteger TraitHandler def validate self object name value if type value is types IntType and value gt 0 and value 2 1 return value self error object name value def info self return x xa positive odd integer An application could use this new trait handler to define traits such as the following use_custom_th py Example of using a custom TraitHandler from traits api import HasTraits Trait TraitRange from custom_traithandler import TraitOddInteger class AnOddClass HasTraits oddball Trait 1l TraitOddInteger 1 1 Traits 4 User Manual 31 Traits 4 User Manual Release 4 6 0 dev354 very odd Trait 1 TraitOddInteger TraitRange 10 1 The following example demonstrates why the info method returns a phrase rather than a complete sentence gt gt gt from use_custom_th import AnOddClass gt gt gt odd stuff AnOddClass
47. object can be built that provides the protocol Defining Adapters The Adapter class The Traits package provides two classes for defining adapters one for Traits adapters Adapter and one for for pure Python adapters PurePythonAdapter These classes streamline the process of creating a new adapter class They have a standard constructor that does not normally need to be overridden by subclasses This constructor accepts one parameter which is the object to be adapted and assigns that object to an adaptee attribute a trait in the case of Adapter As an adapter writer you need to take care of the following e Declare which interfaces the adapter class implements on behalf of the object it is adapting For example if we are working with Traits Interface s the adapter would be decorated with the provides decorator In the case of Python ABCs the class would be a subclass of the abstract base class or be registered with it e Implement the methods defined in the interfaces declared in the previous step Usually these methods are implemented using appropriate members on the adaptee object e For Traits adapters define a trait attribute named adaptee that declares what type of object it is an adapter for Usually this is an Instance trait The following code example shows a definition of a simple adapter class from traits api import Adapter Instance provides Declare what interfaces this adapter implements for its client
48. of using traits from traits api import HasTraits Float class Person HasTraits weight Float 150 0 In this example the attribute named weight specifies that the class has a corresponding trait called weight The value associated with the attribute weight i e Float 150 0 specifies a predefined trait provided with the Traits package which requires that values assigned be of the standard Python type float The value 150 0 specifies the default value of the trait The value associated with each class level attribute determines the characteristics of the instance attribute identified by the attribute name For example 4 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 gt gt gt from minimal import Person gt gt gt instantiate the class gt gt gt joe Person gt gt gt Show the default value gt gt gt joe weight 150 0 gt gt gt Assign new values gt gt gt joe weight 161 9 OK to assign a float gt gt gt joe weight 162 OK to assign an int gt gt gt joe weight average Error to assign a string Traceback most recent call last traits trait_errors TraitError The weight trait of a Person instance must be a float but a value of average lt type str gt was specified In this example joe is an instance of the Person class defined in the previous example The joe object has an instance attribute weight whose initial
49. specified the values are loaded from the in memory object and are not persisted when the dialog box is closed view View or str A View object or its name that defines a user interface for editing trait attribute values of the current object If the view is defined as an attribute on this class use the name of the attribute Otherwise use a reference to the view object If this attribute is not specified the View object returned by trait_view is used kind str The type of user interface window to create See the traitsui view kind_trait trait for values and their meanings If kind is unspecified or None the kind attribute of the View object is used edit bool Indicates whether to display a user interface If filename specifies an exist ing file setting edit to False loads the saved values from that file into the object without requiring user interaction context object or dictionary A single object or a dictionary of string object pairs whose trait attributes are to be edited If not specified the current object is used handler Handler A handler object used for event handling in the dialog box If None the default handler for Traits UI is used id str A unique ID for persisting preferences about this user interface such as size and position If not specified no user preferences are saved scrollable bool Indicates whether the dialog box should be scrollable When set to True scroll ba
50. this decorator is normally effective immediately However if post_init is True then the handler only become effective after all object constructor arguments have been processed That is trait values assigned as part of object construction will not cause the handler to be invoked traits has_traits property_depends_on dependency settable False flushable False Marks the following method definition as being a cached property that depends on the specified extended trait names That is itis a property getter which for performance reasons caches its most recently computed result in an attribute whose name is of the form _traits_cache_name where name is the name of the property A method marked as being a cached property needs only to compute and return its result The property_depends_on decorator automatically wraps the decorated method in cache management code that will cache the most recently computed value and flush the cache when any of the specified dependencies are modified thus eliminating the need to write boilerplate cache management code explicitly For example File file_contents Property file_name property depends on file_name def _get_file_contents self fh open self file_name rb result fh read fh close return result In this example accessing the file_contents trait calls the _get_file_contents method only once each time after the file name trait is modified In all other cases
51. to a b when a changes class traits trait_notifiers FastUITraitChangeNotifyWrapper handler owner tar get None Dynamic change notify wrapper dispatching on the UI thread This class is in charge to dispatch trait change events to dynamic listener typically created using the on_trait_change method and the dispatch parameter set to ui or fast ui class traits trait_notifiers NewTraitChangeNotifyWrapper handler owner tar get None Dynamic change notify wrapper dispatching on a new thread This class is in charge to dispatch trait change events to dynamic listener typically created using the on_trait_change method and the dispatch parameter set to new Functions traits trait_notifiers set_ui_handler handler Sets up the user interface thread handler 2 1 API Reference 115 Traits 4 User Manual Release 4 6 0 dev354 ustr_trait Module Defines the UStr type and HasUniqueStrings mixin class for efficiently creating lists of objects containing traits whose string values must be unique within the list class traits ustr_trait UStr owner list_name str_name default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Bases traits trait_handlers TraitType Trait type that ensures that a value assigned to a trait is unique within the list it belongs to str_type lt traits trait_value TraitValue object gt The type value to assign to restore the original list i
52. trait attribute must match the metadata values of all keywords to be included in the result classmethod class_traits metadata Returns a dictionary containing the definitions of all of the trait attributes of the class that match the set of metadata criteria Parameters metadata Criteria for selecting trait attributes Description The keys of the returned dictionary are the trait attribute names and the values are their corresponding trait definition objects If no metadata information is specified then all explicitly defined trait attributes defined for the class are returned Otherwise the metadata keyword dictionary is assumed to define a set of search criteria for selecting trait attributes of interest The metadata dictionary keys correspond to the names of trait metadata attributes to examine and the values correspond to the values the metadata attribute must have in order to be included in the search results The metadata values either may be simple Python values like strings or integers or may be lambda expres sions or functions that return True if the trait attribute is to be included in the result A lambda expression or function must receive a single argument which is the value of the trait metadata attribute being tested If more than one metadata keyword is specified a trait attribute must match the metadata values of all keywords to be included in the result trait_names metadata Returns a list of the n
53. type instancemethod gt The C level fast validator to use info text a method A description of the type of value this trait accepts class traits trait_types Class default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be an old style Python class fast_validate 11 lt type classobj gt The C level fast validator to use info_text an old style class A description of the type of value this trait accepts class traits trait_types Module default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be a Python module fast_validate 11 type module gt The C level fast validator to use info text a module A description of the type of value this trait accepts class traits trait_types Python default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait that provides behavior identical to a standard Python attribute That is it allows any value to be assigned and raises an ValueError if an attempt is made to get the value before one has been assigned It has no default value This trait is most often used in conjunction with wildcard naming See the Traits User Manual for details on wildcards metadata type python The standard metadata for the trait default_value lt undefined gt The default va
54. value Resolves a class originally specified as a string into an actual class then resets the trait so that future calls will be handled by the normal validate method info Returns a description of the trait get default value Returns a tuple of the form default value type default value which describes the default value for this trait resolve_default_value Resolves a class name into a class so that it can be used to return the class as the default value of the trait 108 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 class traits trait_types Event trait None metadata full_info object name value Returns a description of the trait class traits trait_types Button label image None values_trait None style button orientation vertical width_padding 7 height_padding 5 view None metadata Defines a trait whose UI editor is a button class traits trait_types ToolbarButton label image None style toolbar orienta tion vertical width_padding 2 height_padding 2 metadata Defines a trait whose UI editor is a button that can be used on a toolbar class traits trait_types Either traits metadata Defines a trait whose value can be any of of a specified list of traits as_ctrait Returns a CTrait corresponding to the trait defined by this class class traits trait_types Symbol default_value lt traits trait_handlers N
55. value or raises a TraitError if the assigned value is not valid Both TraitHandler and TraitType derive from BaseTraitHandler TraitHandler has a more limited interface The Traits package provides a number of predefined TraitHandler subclasses A few of the predefined trait handler classes are described in the following sections These sections also demonstrate how to define a trait using a trait handler and the Trait factory function For a complete list and descriptions of predefined TraitHandler subclasses refer to the Traits API Reference in the section on the traits trait_handlers module TraitPrefixList The TraitPrefixList handler accepts not only a specified set of strings as values but also any unique prefix substring of those values The value assigned to the trait attribute is the full string that the substring matches For example gt gt gt from traits api import HasTraits Trait gt gt gt from traits api import TraitPrefixList gt gt gt class Alien HasTraits heads Trait one TraitPrefixList one two three gt gt gt alf Alien gt gt gt alf heads o gt gt gt print alf heads one gt gt gt alf heads tw gt gt gt print alf heads two gt gt gt alf heads t Error not a unique prefix Traceback most recent call last File lt stdin gt line 1 in lt module gt File c svn ets3 traits_3 0 3 enthought traits trait_handlers py line 1802 in va
56. value is the default value of the Person weight trait 150 0 and whose assignment is governed by the Person weight trait s validation rules Assigning an integer to weight is acceptable because there is no loss of precision but assigning a float to an Int trait would cause an error The Traits package allows creation of a wide variety of trait types ranging from very simple to very sophisticated The following section presents some of the simpler more commonly used forms Predefined Traits The Traits package includes a large number of predefined traits for commonly used Python data types In the simplest case you can assign the trait name to an attribute of a class derived from HasTraits any instances of the class will have that attribute initialized to the built in default value for the trait For example account_balance Float This statement defines an attribute whose value must be a floating point number and whose initial value is 0 0 the built in default value for Floats If you want to use an initial value other than the built in default you can pass it as an argument to the trait account balance Float 10 0 Most predefined traits are callable and can accept a default value and possibly other arguments all that are callable can also accept metadata as keyword arguments See Other Predefined Traits for information on trait signatures and see Trait Metadata for information on metadata arguments
57. value of the trait default_value 0 The default value for the trait info_text a valid Python expression A description of the type of value this trait accepts is_mapped True Indicate that this is a mapped trait validate object name value Validates that a specified value is valid for this trait post_setattr object name value Performs additional post assignment processing mapped_value value Returns the mapped value for the specified value as_ctrait Returns a CTrait corresponding to the trait defined by this class class traits trait_types PythonValue default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value can be of any type and whose default editor is a Python shell metadata editor function shell editor at 0x7f4497995848 gt The standard metadata for the trait class traits trait_types BaseFile value filter None auto_set False entries 0 exists False metadata Defines a trait whose value must be the name of a file info_text a file name A description of the type of value this trait accepts validate object name value Validates that a specified value is valid for this trait Note The fast validator version performs this check in C class traits trait_types File value filter None auto_set False entries 0 exists False metadata I Defines a trait whose value
58. 100 info traits trait_types Type method 108 info traits traits CTrait method 58 info_text traits trait_types Any attribute 94 info_text traits trait_types BaseBool attribute 97 info text traits trait_types BaseComplex attribute 96 info_text traits trait_types BaseDirectory attribute 104 info_text traits trait_types BaseFile attribute 103 in o text traits trait_types BaseFloat attribute 96 in o text traits trait_types BaselInt attribute 95 info text traits trait_types BaseLong attribute 95 info_text traits trait_types BaseStr attribute 96 info_text traits trait_types BaseUnicode attribute 97 info_text traits trait_types Callable attribute 101 info_text traits trait_types Class attribute 102 info_text traits trait_types Expression attribute 103 info_text traits trait_types Function attribute 102 info_text traits trait_types Method attribute 102 info_text traits trait_types Module attribute 102 info_text traits trait_types Symbol attribute 109 info_text traits trait_types This attribute 101 info_text traits trait_types UUID attribute 109 info_text traits ustr_trait UStr attribute 116 info_text attribute 26 initQ 26 init traits trait_handlers TraitType method 87 indent 138 Index Traits 4 User Manual Release 4 6 0 dev354 init_fast_validate method 108 init_fast_validate traits trait_types Instance method 108 init_fast_
59. 3 TraitString class in traits trait_handlers 88 TraitTuple class in traits trait_handlers 92 TraitType class in traits trait_handlers 86 TraitType class 25 members 26 Index 143 Traits 4 User Manual Release 4 6 0 dev354 Trait Value class in traits trait value 111 Trait Value class 11 TraitWeakRef class in traits trait_handlers 90 transient metadata 47 predefined traits 47 transient metadata attribute 11 true 7 try_trait_cast in module traits traits 60 Tuple class in traits trait_types 105 Tuple 7 type parameter to Trait 27 string 5 Unicode 5 Type class in traits trait_types 108 type traits trait_value TraitValue attribute 111 type traits traits_listener ListenerGroup attribute 113 type traits traits listener Listenerltem attribute 112 type metadata attribute 10 Type 7 types casting 5 6 coercing 5 6 TypeValue in module traits trait_value 111 U undefined 7 Undefined in module traits trait_base 83 Undefined object 20 Unicode trait 5 type 5 Unicode class in traits trait_types 97 Uninitialized in module traits trait_base 82 UnittestTools class in traits testing unittest_tools 121 unpickling HasTraits objects 48 unregister traits traits_listener ListenerBase method 112 unregister traits traits_listener ListenerGroup method 114 unregister traits traits_listener Listenerltem method 113 use_as_default traits
60. 3 0 behavior Earlier versions also did not support the extended trait name syntax accepting only simple trait names Therefore to use the new style behavior of zero parameter handlers be sure to include some aspect of the extended trait name syntax in the name specifier list_notifier py Example of zero parameter handlers for an object containing a list from traits api import HasTraits List class Employee pass 16 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 class Department employees def a_handler def b_handler def c_handler HasTraits dee List Employee print A handler print B handler print C handler fred Employee mary Employee donna Employee dept Department employees fred mary Old style name syntax a_handler is called only if the list is replaced dept on_trait_change a_handler employees b_handler is called if the membership of the list changes dept on_trait_change b_handler employees_items New style name syntax c handler is called if employees or its membership change dept on_trait_change c_handler employees print Changing list items dept employees 1 donna Calls B and C print Replacing list dept employees donna Calls A and C Static Notification The static approach is the most convenient option but it is not
61. 7 register traits traits_listener ListenerBase method 112 post tracer traits util event_tracer ChangeEventRecorder register traits traits_listener ListenerGroup method method 129 114 post_tracer traits util event_tracer MultiThreadChangeEvengiveoq iraits traits_listener Listenerltem method 113 method 129 pre_tracer traits util event_tracer ChangeEventRecorder method 129 register_factory in module traits adaptation adaptation_manager 118 register_factory traits adaptation adaptation_manager AdaptationManage pre_tracer traits util event_tracer MultiThreadChangeEventRecordemethod 117 method 129 predefined traits 5 prefix metadata attribute 10 prefix parameter to initializer methods 22 print_traits traits has_traits HasTraits method 70 priority traits traits_listener ListenerGroup attribute 113 priority traits traits_listener ListenerItem attribute 112 priority traits util trait_documenter TraitDocumenter at tribute 127 Property in module traits traits 58 property traits 46 caching value 46 Property 7 Property in module traits adaptation api 46 property_depends_on in module traits has_traits 80 prototype parameter to PrototypesFrom 22 PrototypedFrom built in class 22 PrototypedFrom class in traits trait_types 103 prototyping 21 examples 23 provides in module traits has_traits 80 provides_protocol in module re
62. 9 fast_validate traits trait_types CUnicode attribute 100 fast_validate traits trait_types Float attribute 96 fast_validate traits trait_types Function attribute 101 fast_validate traits trait_types Int attribute 95 fast_validate traits trait_types Long attribute 95 fast_validate traits trait_types Method attribute 102 fast_validate traits trait_types Module attribute 102 fast_validate traits trait_types Str attribute 97 fast_validate traits trait_types This attribute 101 fast_validate traits trait_types Unicode attribute 97 FastUITraitChangeNotify Wrapper class traits trait_notifiers 115 in get 26 get traits has_traits HasTraits method 64 get_change_event_collector traits util event_tracer MultiThreadRecordContainer method 129 get_default_value 25 32 get_default_value method 87 get_default_value method 94 get_default_value method 107 get_default_value traits trait_types Type method 108 get_delegate_pattern in module traits has_traits 79 get_editor traits trait_handlers BaseTraitHandler method 85 get_editor traits traits CTrait method 57 get_global_adaptation_manager in module traits adaptation adaptation_manager 118 get_help traits traits CTrait method 57 get_home_directory in traits util home_directory 125 get_module_name in module traits trait_base 83 traits trait_handlers TraitType traits trait_numeric Abstract
63. 95 attribute 120 is_list_handler traits traits_listener Listenerltem at tribute 112 is_mapped traits trait_types Expression attribute 103 is_none in module traits trait_base 83 is_none in module traits traits_listener 111 is_not_none in module traits traits_listener 111 is_str in module traits trait_base 83 is_trait_type traits traits CTrait method 57 ISerializable class in traits has_traits 78 Long trait 5 long_validate traits trait_types BaseRange method 104 mapped traits 28 examples 29 mapped_value traits trait_types Expression method 103 member_order traits util trait_documenter TraitDocumenter attribute 127 Index 139 Traits 4 User Manual Release 4 6 0 dev354 MetaCategory class in traits category 62 MetaCategoryObject class in traits category 62 metadata traits trait_types Callable attribute 101 metadata traits trait_types Code attribute 100 metadata traits trait_types Constant attribute 102 metadata traits trait_types Delegate attribute 103 metadata traits trait_types Generic attribute 94 metadata traits trait_types HTML attribute 101 metadata traits trait_types Password attribute 101 metadata traits trait_types Python attribute 102 metadata traits trait_types Python Value attribute 103 metadata attributes accessing 1 examples 11 internal 10 on traits 10 recognized metadata_defined traits traits_listener Listenerl
64. A trait defined in this fashion can accept only values that are contained in the list of permitted values The default value is the first value specified it is also a valid value for assignment gt gt gt from traits api import Enum HasTraits Str gt gt gt class InventorylItem HasTraits name Str String value default is stock Enum None 0 1 2 3 many Enumerated list default value is None gt gt gt hats InventoryItem gt gt gt hats name Stetson gt gt gt print ss ts hats name hats stock Stetson None gt gt gt hats stock 2 OK gt gt gt hats stock many OK gt gt gt hats stock 4 Error value is not in gt gt gt permitted list Traceback most recent call last traits trait_errors TraitError The stock trait of an InventoryItem instance must be None or 0 or 1 or 2 or 3 or many but a value of 4 lt type int gt was specified This defines an InventoryItem class with two trait attributes name and stock The name attribute is simply a string The stock attribute has an initial value of None and can be assigned the values None 0 1 2 3 and many The example then creates an instance of the InventoryItem class named hats and assigns values to its attributes When the list of possible values can change during the lifetime of the object one can specify another trait that holds the list of possible values
65. Array traits trait_types BaseInstance module Index 137 Traits 4 User Manual Release 4 6 0 dev354 get_path in module traits util resource 126 get_resource_path in module traits trait_base 83 get_value traits trait_handlers TraitType method 87 H handle traits traits_listener ListenerBase method 112 handle_dict traits traits_listener ListenerBase method 112 handle_dict traits traits_listener ListenerItem method 113 handle_dict_items method 112 handle_dict_items method 113 handle_dst traits traits_listener Listenerltem method 113 handle_error method 113 handle_list traits traits_listener ListenerBase method 112 handle_list traits traits_listener ListenerItem method 113 handle_list_items method 112 handle_list_items method 113 handle_list_items_special traits traits_listener Listenerltem 113 handle simpleo method 113 traits traits listener ListenerBase traits traits listener Listenerltem traits traits listener Listenerltem traits traits listener ListenerBase traits traits listener Listenerltem method traits traits listener Listenerltem handler signatures 16 handler traits traits listener ListenerGroup 113 handler traits traits_listener ListenerItem attribute 112 handler traits util event_tracer CallingMessageRecord attribute 128 handler traits util event_tracer ExitMessageRecord at tribute 129 handl
66. Float ListFunction ListInstance ListInt ListMethod ListStr ListThis ListUnicode Li Method M Module M Password Pa Property Pr 1 1 Traits 4 User Manual 7 Traits 4 User Manual Release 4 6 0 dev354 Table 1 1 coni Name Ci Python Py Python Value Py Range R ReadOnly Re Regex Re RGBColor R self ni Set Se String St This ni ToolbarButton To true ni Tuple Tu Type Ty undefined ni UStr UUID Ul ValidatedTuple Va WeakRef W This and self A couple of predefined traits that merit special explanation are This and self They are intended for attributes whose values must be of the same class or a subclass as the enclosing class The default value of This is None the default value of self is the object containing the attribute The following is an example of using This this py Example of This predefined trait from traits api import HasTraits This class Employee HasTraits manager TRIS This example defines an Employee class which has a manager trait attribute which accepts only other Employee instances as its value It might be more intuitive to write the following bad_self_ref py Non working example with self referencing class definition from traits api import HasTraits class Employee HasTraits manager Instance Employee Instance However the Employee class is not fully
67. Manual Release 4 6 0 dev354 class traits traits_listener ListenerBase Bases traits has_traits HasPrivateTraits register new Registers new listeners unregister old Unregisters any existing listeners handle object name old new Handles a trait change for a simple trait handle_list object name old new Handles a trait change for a list trait handle_list_items object name old new Handles a trait change for a list traits items handle_dict object name old new Handles a trait change for a dictionary trait handle_dict_items object name old new Handles a trait change for a dictionary traits items class traits traits_listener ListenerItem Bases traits traits_listener ListenerBase name Str The name of the trait to listen to metadata_name Str The name of any metadata that must be present or not present metadata_defined Bool True Does the specified metadata need to be defined True or not defined False handler Any The handler to be called when any listened to trait is changed wrapped_handler_ref Any A weakref wrapped version of handler dispatch Str The dispatch mechanism to use when invoking the handler priority Bool False Does the handler go at the beginning True or end False of the notification handlers list next Instance ListenerBase The next level if any of ListenerBase object to be called when any of this object s li
68. Slider HasTraits def init self eval None label Value trait None min 0 0 max 1 0 initial None xtraits HasTraits init__ self traits if trait is None if min gt max min max max min if initial is None initial min elif not min lt initial lt max initial min max abs initial min gt abs initial max trait Range min max value initial self add_trait label trait This example creates a GUISlider class whose __init__ method can accept a string label and either a trait definition or minimum maximum and initial values If no trait definition is specified one is constructed based on the max and min values A trait attribute whose name is the value of label is added to the object using the trait definition whether specified or constructed Thus the label trait attribute on the GUISlider object is determined by the calling code and added in the __init__ method using add_trait You can require that add_trait must be used in order to add attributes to a class by deriving the class from HasStrict Traits see HasStrictTraits When a class inherits from HasStrictTraits the program cannot create a new attribute either a trait attribute or a regular attribute simply by assigning to it as is normally the case in Python In this case add_trait is the only way to create a new attribute for the class outside of the class definition 36 Chapter 1 User Reference
69. String value minlen 0 maxlen 9223372036854775807 regex metadata Defines a trait whose value must be a Python string whose length is optionally in a specified range and which optionally matches a specified regular expression validate object name value Validates that the value is a valid string validate_all object name value Validates that the value is a valid string in the specified length range which matches the specified regular expression validate_str object name value Validates that the value is a valid string validate_len object name value Validates that the value is a valid string in the specified length range validate_regex object name value Validates that the value is a valid string which matches the specified regular expression info Returns a description of the trait create editor Returns the default traits UI editor for this type of trait class traits trait_types Regex value regex metadata Defines a trait whose value is a Python string that matches a specified regular expression class traits trait_types Code value minlen 0 maxlen 9223372036854775807 regex metadata Defines a trait whose value is a Python string that represents source code in some language 100 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 metadata editor function code editor at 0x7f4497995758 gt The s
70. _name Chase Parent s last name changed to Chase gt gt gt son Child first_name John father dad Child s last name changed to Chase gt gt gt dad last_name Jones Parent s last name changed to Jones Child s last name changed to Jones gt gt gt son last_name Thomas Child s last name changed to Thomas gt gt gt dad last_name Riley Parent s last name changed to Riley gt gt gt del son last_name Child s last name changed to Riley gt gt gt dad last_name Simmons Parent s last name changed to Simmons Child s last name changed to Simmons nnn Initially changing the last name of the father triggers notification on both the father and the son Explicitly setting the son s last name breaks the deferring link to the father therefore changing the father s last name does not notify the son When the son reverts to using the father s last name by deleting the explicit value changes to the father s last name again affect and notif 1 1 6 Custom Traits The predefined traits such as those described in Predefined Traits are handy shortcuts for commonly used types However the Traits package also provides facilities for defining complex or customized traits 24 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 e Subclassing of traits e The Trait factory function Predefined or custom trait handlers Trait Subclassing Starting with Traits versio
71. _types 97 Str trait 5 str_type traits ustr_trait UStr attribute 116 string type 5 String class in traits trait_types 100 strx in module traits trait_base 83 subclassing traits 25 examples 25 Supports class in traits trait_types 108 sync_trait traits has_traits HasTraits method 75 SyncValue in module traits trait_value 111 syntax extended trait names 14 on_trait_change 17 T test trait classes 51 testing 51 text traits traits_listener ListenerParser attribute 114 This 7 This class in traits trait_types 101 This trait 8 examples 8 ThisClass class in traits trait_handlers 90 Time in module traits trait_types 109 time traits util event_tracer CallingMessageRecord at tribute 128 time traits util event_tracer ChangeMessageRecord at tribute 128 traits util event_tracer ExitMessageRecord at tribute 129 time editor in module traits traits 60 Title class in traits trait_types 97 to_protocol traits adaptation adaptation_offer AdaptationOffer attribute 119 ToolbarButton class in traits trait_types 109 ToolbarButton 7 topological_sort in module traits util toposort 127 trace trait change events 53 trait definitions reusing 33 parameter to Trait 27 trait attributes per object 36 trait change handler signatures 16 trait handler classes 30 parameter to Trait 27 trait property defining 26 Trait 27 parameters 27 Trait in module tra
72. ait and an event e All notification handlers associated with an event are called whenever any value is assigned to the event A normal trait attribute only calls its associated notification handlers when the previous value of the attribute is different from the new value being assigned to it e An event does not use any storage and in fact does not store the values assigned to it Any value assigned to an event is reported as the new value to all associated notification handlers and then immediately discarded Because events do not retain a value the old argument to a notification handler associated with an event is always the special Undefined object see Undefined Object Similarly attempting to read the value of an event results in a TraitError exception because an event has no value As an example of an event consider event py Example of trait event from traits api import Event HasTraits List Tuple point_2d Tuple 0 0 class Line2D HasTraits points List point_2d line_color RGBAColor black updated Event def redraw self pass Not implemented for this example def _points_changed self self updated True def _updated_fired self self redraw In support of the use of events the Traits package understands attribute specific notification handlers with names of the form _name_fired with signatures identical to the _name_changed functions In fact the Traits package does not
73. ait_change number def _add_number_to_list self value 1 1 Traits 4 User Manual 51 Traits 4 User Manual Release 4 6 0 dev354 oon mu Append the value to the list of numbers self list_of_numbers append value def add_to_number self value Add the value to number self number value class MyTestCase unittest TestCase UnittestTools def setUp self self my_class MyClass def test_when_using_with self Check normal use cases as a context manager won my_class self my_class Checking for change events with self assertTraitChanges my_class number as result my_class number 5 0 Inspecting the last recorded event expected my_class number 2 0 5 0 self assertSequenceEqual result events expected Checking for specific number of events with self assertTraitChanges my_class number count 3 as result my_class flag True my_class add_to_number 10 0 my_class add_to_number 10 0 my_class add_to_number 10 0 expected my_class number 5 0 15 0 my_class number 15 0 25 0 my_class number 25 0 35 0 self assertSequenceEqual result events xpected Check using extended names with self assertTraitChanges my_class list_of_numbers my_class number 3 0 Check that event is not fired my_class number 2 0 with self assertTraitDoesNotChange my_class number as result my_
74. ait_types List object gt List of string values default value is traits trait_types ListUnicode lt traits trait_types List object gt List of Unicode string values default value is traits trait_types ListComplex lt traits trait_types List object gt List of complex values default value is 2 1 API Reference 109 Traits 4 User Manual Release 4 6 0 dev354 traits trait_types ListBool lt traits trait_types List object gt List of Boolean values default value is traits trait_types ListFunction lt traits trait_types List object gt List of function values default value is traits trait_types ListMethod lt traits trait_types List object gt List of method values default value is traits trait_types ListClass lt traits trait_types List object gt List of class values default value is traits trait_types ListInstance lt traits trait_types List object gt List of instance values default value is traits trait_types ListThis lt traits trait_types List object gt List of container type values default value is traits trait_types DictStrAny lt traits trait_types Dict object gt Only a dictionary of string Any values can be assigned only string keys can be inserted The default value is traits trait_types DictStrStr lt traits trait_types Dict object gt Only a dictionary of string string values can be assigned only string keys with string values can b
75. aits_listener ListenerNotify Wrapper method 114 140 Index Traits 4 User Manual Release 4 6 0 dev354 P parent metadata attribute 10 parse traits traits listener ListenerParser method 14 parse_group traits traits_listener ListenerParser method 114 parse_item traits traits_listener ListenerParser method 114 parse_metadata traits traits_listener ListenerParser method 114 Password class in traits trait_types 101 Password 7 password_editor in module traits traits 60 performance of Traits 50 performance in module traits testing nose_tools 121 persistence 47 pickling HasTraits objects 47 plain integer type 5 post setattr 26 post setattr traits trait types Expression method 103 post setattr traits trait types Supports method 108 PurePythonAdapter class in traits adaptation adapter 119 Python class in traits trait_types 102 Python 7 python_name in module traits util clean_strings 125 Python Value class in traits trait_types 103 Python Value 7 R Range class in traits trait_types 104 Range 7 ReadOnly in module traits trait_types 102 ReadOnlyO 7 recognized metadata attributes record traits util event_tracer RecordContainer method 129 record_events in module traits util event_tracer 130 RecordContainer class in traits util event_tracer 129 Regex class in traits trait_types 100 Regex
76. alid for this trait Note The fast validator version performs this check in C class traits trait_types CComplex default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be a Python complex and which supports coercions of non complex values to complex using a C level fast validator fast_validate 12 lt type complex gt The C level fast validator to use class traits trait_types BaseCStr default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be a Python string and which supports coercions of non string values to string validate object name value Validates that a specified value is valid for this trait Note The fast validator version performs this check in C class traits trait_types CStr default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be a Python string and which supports coercions of non string values to string using a C level fast validator fast_validate 7 12 lt type str gt 12 lt type unicode gt The C level fast validator to use class traits trait_types BaseCUnicode default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be a Python unicode string and which supports coercions of non unicode values to u
77. allowance Float 1 00 class Child HasTraits __prefix__ child_ first name PrototypedFrom mother favorite_ last_name PrototypedFrom father family_name allowance PrototypedFrom father x father Instance Parent mother Instance Parent non gt gt gt fred Parent first name Fred family name Lopez favorite_first_name Diego child_allowance 5 0 gt gt gt maria Parent first name Maria family name Gonzalez favorite first_name Tomas child_allowance 10 0 gt gt gt nino Child father fred mother maria gt gt gt print ts bs gets 2f for allowance nino first_name nino last_name niy Tomas Lopez gets 5 00 for allowance non In this example instances of the Child class have three prototyped trait attributes e first name which prototypes from the favorite first name attribute of its mother object e last name which prototyped from the family name attribute of its father object e allowance which prototypes from the child_allowance attribute of its father object Listenable Keyword By default you can attach listeners to deferred trait attributes just as you can attach listeners to most other trait attributes as described in the following section However implementing the notifications correctly requires hooking up complicated listeners under the covers Hooking up these listeners can be rather more expensive than hoo
78. alty on attribute access over and above that of normal Python attributes For the most part this penalty if any is small because the core of the Traits package is written in C just like the Python interpreter In fact for some common cases subclasses of HasTraits can actually have the same or better performance than old or new style Python classes However there are a couple of performance related factors to keep in mind when defining classes and attributes using traits e Whether a trait attribute defers its value through delegation or prototyping e The complexity of a trait definition If a trait attribute does not defer its value the performance penalty can be characterized as follows e Getting a value No penalty i e standard Python attribute access speed or faster e Setting a value Depends upon the complexity of the validation tests performed by the trait definition Many of the predefined trait handlers defined in the Traits package support fast C level validation For most of these the cost of validation is usually negligible For other trait handlers with Python level validation methods the cost can be quite a bit higher If a trait attribute does defer its value the cases to be considered are 50 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 e Getting the default value Cost of following the deferral chain The chain is resolved at the C level and is quite fast but its cost is lin
79. ames of all trait attributes whose definitions match the set of metadata criteria specified Parameters metadata Criteria for selecting trait attributes 2 1 API Reference 77 Traits 4 User Manual Release 4 6 0 dev354 Description This method is similar to the traits method but returns only the names of the matching trait attributes not the trait definitions classmethod class_trait_names metadata Returns a list of the names of all trait attributes whose definitions match the set of metadata criteria specified Parameters metadata Criteria for selecting trait attributes Description This method is similar to the traits method but returns only the names of the matching trait attributes not the trait definitions class traits has_traits HasStrictTraits This class guarantees that any object attribute that does not have an explicit or wildcard trait definition results in an exception This feature can be useful in cases where a more rigorous software engineering approach is being used than is typical for Python programs It also helps prevent typos and spelling mistakes in attribute names from going unnoticed a misspelled attribute name typically causes an exception class traits has_traits HasPrivateTraits This class ensures that any public object attribute that does not have an explicit or wildcard trait definition results in an exception but private attributes whose names start with _
80. andler Setting up a dynamic trait attribute change notification handler is illustrated in the following example dynamic_notification py Example of dynamic notification from traits api import Float HasTraits Instance class Part HasTraits cost Float 0 0 class Widget HasTraits partl Instance Part part2 Instance Part cost Float 0 0 def init self self partl Part self part2 Part self partl on_trait_change self update_cost cost self part2 on_trait_change self update_cost cost 1 1 Traits 4 User Manual 13 Traits 4 User Manual Release 4 6 0 dev354 def update_cost self self cost self partl cost self part2 cost Example w Widget w partl cost 2 25 w part2 cost 5 31 print w cost Result 7 56 In this example the Widget constructor sets up a dynamic trait attribute change notification so that its update_cost method is called whenever the cost attribute of either its part1 or part2 attribute is modified This method then updates the cost attribute of the widget object The name Parameter The name parameter of on_trait_change and on_trait_event provides significant flexibility in specifying the name or names of one or more trait attributes that the handler applies to It supports syntax for specifying names of trait attributes not just directly on the current object but also on sub objects referenced by the current object The
81. ass if name __main_ This will run and report both FooTestCase and the doctests in module foo unittest main Alternatively you can say FooDocTest doctest_for_module foo instead of class FooDocTest doctest_for_module foo pass nose_tools Module Non standard functions for the nose testing framework traits testing nose_tools skip f Stub replacement for marking a unit test to be skipped in the absence of nose traits testing nose_tools deprecated f Stub replacement for marking a unit test deprecated in the absence of nose traits testing nose_tools performance f Decorator to add an attribute to the test to mark it as a performance measuring test trait_assert_tools Module Trait assert mixin class to simplify test implementation for Trait Classes traits testing unittest_tools reverse_assertion args kwds class traits testing unittest_tools UnittestTools Bases object 2 1 API Reference 121 Traits 4 User Manual Release 4 6 0 dev354 Mixin class to augment the unittest TestCase class with useful trait related assert methods assertTraitChanges obj trait count None callableObj None args kwargs Assert an object trait changes a given number of times Assert that the class trait changes exactly count times during execution of the provided function This method can also be used in a with statement to assert that a class trai
82. ator to use class traits trait_types BaseCInt default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be a Python int and which supports coercions of non int values to int evaluate The function to use for evaluating strings to this type alias of int validate object name value Validates that a specified value is valid for this trait Note The fast validator version performs this check in C class traits trait_types CInt default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be a Python int and which supports coercions of non int values to int using a C level fast validator fast_validate 12 lt type int gt The C level fast validator to use class traits trait_types BaseCLong default_value lt traits trait_handlers NoDefaultSpecified ob ject gt metadata Defines a trait whose value must be a Python long and which supports coercions of non long values to long evaluate The function to use for evaluating strings to this type alias of long validate object name value Validates that a specified value is valid for this trait Note The fast validator version performs this check in C class traits trait_types CLong default_value lt traits trait_handlers NoDefaultSpecified objects metadata Defines a trait whose value must be a Python long and which su
83. attribute changes are to be monitored or if you want to monitor changes on certain instances of a class but not all of them To use dynamic notification you define a handler method or function and then invoke the on_trait_change or on_trait_event method to register that handler with the object being monitored Multiple handlers can be defined for the same object or even for the same trait attribute on the same object The handler registration methods have the following signatures on_trait_change handler name None remove False dispatch same on_trait_event handler name None remove False dispatch same J In these signatures e handler Specifies the function or bound method to be called whenever the trait attributes specified by the name parameter are modified e name Specifies trait attributes whose changes trigger the handler being called If this parameter is omitted or is None the handler is called whenever any trait attribute of the object is modified The syntax supported by this parameter is discussed in The name Parameter e remove If True or non zero then handler will no longer be called when the specified trait attributes are modified In other words it causes the handler to be unhooked e dispatch String indicating the thread on which notifications must be run In most cases it can be omitted See the Traits API Reference for details on non default values Example of a Dynamic Notification H
84. ay that the Instance trait accepts values that provide the specified protocol Traits defines two additional traits that accept values that support a given protocol they provide it or can be adapted to it instead e The Supports trait accepts values that support the specified protocol The value of the trait after assignment is the possibly adapted value i e it is the original assigned value if that provides the protocol or is an adapter otherwise e The Adapt sTo trait also accepts values that support the specified protocol Unlike Supports AdaptsTo stores the original unadapted value If your application works with adaptation it is natural to use the Supports trait in place of the Instance one in most cases This will allow that application to be extended by adaptation in the future without changing the existing code without having to invoke adaptation explicitly in your code For example a Traits object can be written against the TPrint able interface and be open to extensions by adaptation as follows from traits api import Adapter HasTraits Interface List provides register_factory Str Supports class IPrintable Interface def get_formatted_text self n_cols mm Return text formatted with the given number of columns class PrintQueue HasTraits This is the key part of the example we declare a list of items that provide or can be adapted to IPrintable queue List Supports IPrintable
85. ayed Note trait is a synonym for property but is used instead of the word property to differentiate it from the Python language property feature Classes class traits traits CTrait Extends the underlying C based cTrait type is_trait_type trait_type Returns whether or not this trait is of a specified trait type get_editor Returns the user interface editor associated with the trait get_help full True Returns the help text for a trait Parameters full bool Indicates whether to return the value of the help attribute of the trait itself 57 Traits 4 User Manual Release 4 6 0 dev354 Description If full is False or the trait does not have a help string the returned string is constructed from the desc attribute on the trait and the info string on the trait s handler full_info object name value Returns a description of the trait info Returns a description of the trait class traits traits TraitFactory maker_function None class traits traits TraitImportError message Defines a factory class for deferring import problems until encountering code that actually tries to use the unimportable trait class traits traits Default func None args kw None Generates a value the first time it is accessed A Default object can be used anywhere a default trait value would normally be specified to generate a default value dynamically traits traits Property
86. behaves nicely with MetaHasTraits provided it is inherited first class traits has_traits ABCHasTraits A HasTraits subclass which enables the features of Abstract Base Classes ABC See the abc module in the standard library for more information class traits has_traits ABCHasStrictTraits A HasTraits subclass which behaves like HasStrictTraits but also enables the features of Abstract Base Classes ABC See the abc module in the standard library for more information Functions traits has_traits cached_property function Marks the following method definition as being a cached property That is it is a property getter which for performance reasons caches its most recently computed result in an attribute whose name is of the form _traits_cache_name where name is the name of the property A method marked as being a cached property needs only to compute and return its result The cached_property decorator automatically wraps the decorated method in cache management code eliminating the need to write boilerplate cache management code explicitly For example file_name File file_contents Property depends_on file_name cached_property def _get_file_contents self fh open self file_name rb result fh read fh close return result In this example accessing the file_contents trait calls the _get_file_contents method only once each time after the file_name trait is modified In a
87. bute 111 L label metadata attribute 11 len text traits traits_listener ListenerParser attribute 114 List class in traits trait_types 106 List 7 ListBool in module traits trait_types 109 ListClass in module traits trait_types 110 ListComplex in module traits trait_types 109 listenable parameter to initializer methods 23 listener traits traits_listener ListenerParser attribute 114 listener_deleted _ traits traits_listener ListenerHandler method 114 listener_deleted traits traits_listener ListenerNotifyWrapper method 114 ListenerBase class in traits traits_listener 111 ListenerGroup class in traits traits_listener 113 ListenerHandler class in traits traits_listener 114 ListenerItem class in traits traits_listener 112 ListenerNotifyWrapper class in traits traits_listener 114 ListenerParser class in traits traits_listener 114 ListFloat in module traits trait_types 109 ListFunction in module traits trait_types 110 ListInstance in module traits trait_types 110 ListInt in module traits trait_types 109 ListMethod in module traits trait_types 110 ListStr in module traits trait_types 109 ListThis in module traits trait_types 110 ListUnicode in module traits trait_types 109 long integer type 5 is_empty traits adaptation cached_adapter_factory Cache erHacto i pty traits adaptati hed_adapter_factory Cach dA dap RS AY traits trait_types
88. cally as part of the body of the class definition This occurs for example when two classes with trait attributes are being defined and each class has a trait attribute that should contain a reference to the other For the class that occurs first in lexical order it is not possible to define the trait attribute that references the other class since the class it needs to refer to has not yet been defined This is illustrated in the following example circular_definition py Non working example of mutually referring classes from traits api import HasTraits Trait class Chicken HasTraits hatched_from Trait Egg class Egg HasTraits created_by Trait Chicken As it stands this example will not run because the hatched_from attribute references the Egg class which has not yet been defined Reversing the definition order of the classes does not fix the problem because then the created_by trait references the Chicken class which has not yet been defined The problem can be solved using the add_class_trait method as shown in the following code add class trait py Example of mutually referring classes using add class trait from traits api import HasTraits Trait class Chicken HasTraits pass class Egg HasTraits created by Trait Chicken Chicken add_class_trait hatched_from Egg Performance Considerations of Traits Using traits can potentially impose a performance pen
89. came at a cost e When the value of an attribute was used by an object internally for example setting the correct pen color when drawing a plot line the object would often have to map the user supplied value to a suitable internal 1 1 Traits 4 User Manual 3 Traits 4 User Manual Release 4 6 0 dev354 representation a potentially expensive operation in some cases e If the user supplied a value outside the realm accepted by the object internally it often caused disastrous or mysterious program behavior This behavior was often difficult to track down because the cause and effect were usually widely separated in terms of the logic flow of the program So one of the main goals of the Traits package is to provide a form of type checking that e Allows for flexibility in the set of values an attribute can have such as allowing red OxFFOO00 and 1 0 0 0 0 0 1 0 as equivalent ways of expressing the color red e Catches illegal value assignments at the point of error and provides a meaningful and useful explanation of the error and the set of allowable values e Eliminates the need for an object s implementation to map user supplied attribute values into a separate internal representation In the process of meeting these design goals the Traits package evolved into a useful component in its own right satisfying all of the above requirements and introducing several additional powerful features of its own In p
90. ce We provide this class to provide the caching functionality of the old traits adapts implementation However note that the cache will not be cleared unless you take care of cleaning the adaptee trait once your adapter are deleted 2 1 API Reference 119 Traits 4 User Manual Release 4 6 0 dev354 This class will be removed when the adapts function is removed factory adapter A callable that actually creates the adapters The factory must ba callable that takes exactly one argument which is the object to be adapted known as the adaptee and returns an adapter from the from_protocol to the to_protocol The factory can be specified as either a callable or a string in the form foo bar baz which is turned into an import statement from foo bar import baz and imported when the trait is first accessed is_empty Property Bool True if the cache is empty otherwise False This method is mostly here to help testing the framework does not rely on it for any other purpose etsconfig Package etsconfig Package Supports sharing settings across projects or programs on the same system Part of the EnthoughtBase project etsconfig Module Enthought Tool Suite configuration information traits etsconfig etsconfig ETSConfig lt traits etsconfig etsconfig ETSConfig object gt Enthought Tool Suite configuration information This class should not use ANY other package in the tool suite so that it
91. change for a list or set trait handle_list_items object name old new Handles a trait change for items of a list or set trait handle_list_items_special object name old new Handles a trait change for items of a list or set trait with notification handle_dict object name old new Handles a trait change for a dictionary trait handle_dict_items object name old new Handles a trait change for items of a dictionary trait handle_error obj name old new Handles an invalid intermediate trait change to a handler that must be applied to the final destination object trait class traits traits_listener ListenerGroup Bases traits traits_listener ListenerBase handler Property The handler to be called when any listened to trait is changed wrapped_handler_ref Property A weakref wrapped version of handler dispatch Property The dispatch mechanism to use when invoking the handler priority ListProperty Does the handler go at the beginning True or end False of the notification handlers list next ListProperty The next level if any of ListenerBase object to be called when any of this object s listened to traits is changed type ListProperty The type of handler being used notify ListProperty Should changes to this item generate a notification to the handler 2 1 API Reference 113 Traits 4 User Manual Release 4 6 0 dev354 deferred ListProperty Should registering
92. changed or _name_fired The leading underscore indicates that attribute specific notification handlers are normally part of a class s private API Methods named _name_fired are normally used with traits that are events described in Trait Events To notify about changes to any trait attribute on a class define a method named _anytrait_changed Both of these types of static trait attribute notification methods are illustrated in the following example static_notification py Example of static attribute notification from traits api import HasTraits Float class Person HasTraits weight kg Float 0 0 height_m Float 1 0 bmi Float 0 0 def weight kg changed self old new print weight kg changed from s to s old new if self height m 0 0 self bmi self weight_kg self height_m 2 def _anytrait_changed self name old new print The s trait changed from s to s o 5 name old new gt gt gt bob Person gt gt gt bob height_m 1 75 The height m trait changed from 1 0 to 1 75 gt gt gt bob weight_kg 100 0 The weight_kg trait changed from 0 0 to 100 0 weight_kg changed from 0 0 to 100 0 The bmi trait changed from 0 0 to 32 6530612245 non 18 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 In this example the attribute specific notification function is weight kg changed which is called only when the weight_kg a
93. class flag True my_class number 2 0 The value is the same as the original Using Mocks Trying to mock a method in a HasStrictTraits instance will raise an error because the HasStrictTraits machinery does not allow any modification of the methods and attributes of a HasStrictTraits instance To circumvent the HasSt rictTraits machinery and mock methods using the mock library please follow the logic in the example below 52 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 from traits api import HasStrictTraits Float from mock import Mock class MyClass HasStrictTraits number Float 2 0 def add_to_number self value Add the value to number self number value my class MyClass Using my_class add_to_number Mock will fail But setting the mock on the instance __dict__ works my_class __dict add_to_number Mock We can now use the mock in our tests my_class add_number 42 print my_class add_to_number call_args_list Note The above method will not work for mocking Property setters getters and validators 1 1 9 Tips for debugging Traits Re raising exceptions in change handlers Traits will typically log instead of raise exceptions when an exception is encountered in a trait change handler This behavior is often preferred in applications since you usually want to avoid critical failures in applications However wh
94. ct Parameters name str Name of the attribute to remove Returns result bool True if the trait was successfully removed trait name force False copy False Returns the trait definition for the name trait attribute Parameters e name str Name of the attribute whose trait definition is to be returned e force bool Indicates whether to return a trait definition if name is not explicitly defined e copy bool Indicates whether to return the original trait definition or a copy Description If force is False the default and name is the name of an implicitly defined trait attribute that has never been referenced explicitly i e has not yet been defined the result is None In all other cases the result is the trait definition object associated with name If copy is True and a valid trait definition is found for name a copy of the trait found is returned In all other cases the trait definition found is returned unmodified the default base_trait name Returns the base trait definition for a trait attribute Parameters name str Name of the attribute whose trait definition is returned Description This method is similar to the trait method and returns a different result only in the case where the trait attribute defined by name is a delegate In this case the base_trait method follows the delegation chain until a non delegated trait attribute is reached and returns the definition of
95. d 97 validate traits trait_types Callable method 101 validate traits trait_types CList method 106 validate traits trait_types CSet method 107 validate traits trait_types Dict method 107 validate traits trait_types Expression method 103 validate traits trait_types List method 106 validate traits trait_types Set method 106 validate traits trait_types String method 100 validate traits trait_types Type method 108 validate traits trait types UUID method 109 validate traits trait_types ValidatedTuple method 106 validate traits ustr_trait UStr method 116 validate_all traits trait_types String method 100 validate_len traits trait_types String method 100 validate_regex traits trait_types String method 100 validate_str traits trait_types String method 100 validate_trait traits has_traits HasTraits method 76 ValidatedTuple class in traits trait_types 105 ValidatedTuple 7 validation 2 4 value parameter validate 26 verify_pathQ in module traits trait_base 83 Vetoable class in traits has_traits 78 ViewElement class in traits has_traits 62 visible_traits traits has_traits HasTraits method 70 visualization 2 W wait_for_condition in traits util async_trait_wait 124 weak_arg in module traits has_traits 80 module 144 Index Traits 4 User Manual Release 4 6 0 dev354 WeakRef class in traits trait_types 109 WeakR
96. d allowed tuples If the first item of types is a tuple it is used as the default value The remaining argument list is used to form a tuple that constrains the values assigned to the returned trait The trait s value must be a tuple of the same length as the remaining argument list whose elements must match the types specified by the corresponding items of the remaining argument list Default Value 1 If no arguments are specified the default value is 2 If a tuple is specified as the first argument it is the default value 3 If a tuple is not specified as the first argument the default value is a tuple whose length is the length of the argument list and whose values are the default values for the corresponding trait types Example for case 2 mytuple Tuple Fred Betty 5 The trait s value must be a 3 element tuple whose first and second elements are strings and whose third element is an integer The default value is Fred Betty 5 Example for case 3 mytuple Tuple Fred Betty 5 The trait s value must be a 3 element tuple whose first and second elements are strings and whose third element is an integer The default value is 0 init_fast_validator args Saves the validation parameters validate object name value Validates that the value is a valid tuple full_info object name value Returns a description of the trait create editor
97. d get name which takes no arguments and returns a string Do not include any implementation code in an interface declaration However the Traits package does not actually check to ensure that interfaces do not contain implementations By convention interface names have a capital T at the beginning of the name Implementing an Interface A class declares that it implements one or more interfaces using the provides class decorator which has the signature traits has_traits provides interface interface2 interfaceN Interface names beyond the first one are optional As for all class decorators the call to provides must occur just before the class definition For example from traits api import HasTraits Interface provides Str class IName Interface def get_name self Returns a string which is the name of an object provides IName class Person HasTraits first name Str John last name Str Doe Implementation of the IName interface def get_name self Returns the name of an object 1 1 Traits 4 User Manual 37 Traits 4 User Manual Release 4 6 0 dev354 name first last return name format name self first_name last self last_name You can specify whether the provides decorator verifies that the class calling it actually implements the interface that it says it does This is determined by the CHECK_INTERFACES variable
98. d trace in the local folder The file contents will be similar to the lines below 2014 03 21 14 11 20 779000 gt number changed from 2 0 to 4 7 in MyModel 2014 03 21 14 11 20 779000 CALLING _add_number_to_list in example py 2014 03 21 14 11 20 780000 gt list_of_numbers_items changed from lt undefined gt to lt traits trait_hal 2014 03 21 14 11 20 780000 CALLING handle_list_items_special in C Users itziakos Projects t 2014 03 21 14511620 780000 gt list of numbers items changed from to 4 7 in MyModel 2014 03 21 14 11 20 780000 CALLING count items in exampler py 2014 05 21 14 11 20 780000 gt trait_added changed from lt undefined gt to list_on_mumbers in I 2014 03 21 14 11 20 780000 CALLING _trait_added_changed in C Users itziakos Projects t 2014 03 21 14211220 780000 lt EXI _trait_added_changed 2014 03 21 14211220 780000 lt EXIT count items EXCEPTION MyModel object has no attribute 2014 03 21 14 11 20 780000 lt EXIT handle_list_items_special 2014 03 21 14 11 20 781000 lt EXIT _add_number_to_list 2014 03 21 14 11 20 781000 gt number changed from 4 7 to 3 0 in MyModel 2014 03 21 14 11 20 781000 CALLING _add_number_to_list in example py 2014 03 21 14 11 20 781000 gt list of numbers items changed from lt undefined gt to lt traits trait_
99. daptee to to_protocol If no such adaptation is possible then either an AdaptationError is raised if default Adaptation error or default is returned as in the default value passed to getattr etc register_offer offer Register an offer to adapt from one protocol to another register_factory factory from_protocol to_protocol Register an adapter factory This is a simply a convenience method that creates and registers an AdaptationOffer from the given arguments register_provides provider_protocol protocol Register that a protocol provides another supports_protocol obj protocol Does the object support a given protocol An object supports a protocol if either it provides it directly or it can be adapted to it 2 1 API Reference 117 Traits 4 User Manual Release 4 6 0 dev354 traits adaptation adaptation_manager adaptation_manager lt traits adaptation adaptation_manager Adapta The default global adaptation manager PROVIDED FOR BACKWARD COMPATIBILITY ONLY IT SHOULD NEVER BE USED DIRECTLY If you must use a global adaptation manager use the functions get_global_adaptation_manager reset_global_adaptation_manager set_global_adaptation_manager traits adaptation adaptation_manager set_global_adaptation_manager new_adaptation_manager Set the global adaptation manager to the given instance traits adaptation adaptation_manager reset_global_adaptation_manager Set the global adap
100. def is_empty self return len self queue 0 def push self printable self queue append printable def print_next self printable self queue pop 0 The elements from the list are guaranteed to provide IPrintable so we can call the interface without worrying about adaptation lines printable get_formatted_text n_cols 20 print Start document print n join lines print End of document n class TextDocument HasTraits mun A text document text Str provides IPrintable class TextDocumentToIPrintable Adapter Adapt TextDocument and provide IPrintable def get_formatted_text self n_cols import textwrap 1 1 Traits 4 User Manual 43 Traits 4 User Manual Release 4 6 0 dev354 return textwrap wrap self adaptee text n_cols Application starts here Register the adapter register factory TextDocumentTolIPrintable TextDocument IPrintable Create two text documents docl TextDocument text very very long text the will bore you for sure doc2 TextDocument text once upon a time in a far away galaxy The text documents can be pushed on the print queue in the process they are automatically adapted by Traits print_queue PrintQueue print_queue push docl print gueue push doc2 while not print_queue is_empty print_queue print_next This scripts produces this output
101. e line_color fill_color HasTraits standard_color red_color The GraphicShape class has two attributes line_color and fill_color These attributes are defined in terms of the standard_color trait which uses a dictionary The standard_color trait is a mapped trait which means that each GraphicShape instance has two shadow attributes line_color_ and fill_color_ Any time a new value is assigned to either line_color or fill_color the corresponding shadow attribute is updated with the value in the dictionary corre sponding to the value assigned For example gt gt gt import mapped gt gt gt my_shapel mapped GraphicShape gt gt gt print my_shapel line_color my_shapel fill_color black red gt gt gt print my_shapel line_color_ my_shapel fill_color_ 0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 gt gt gt my_shape2 mapped GraphicShape gt gt gt my_shape2 line_color blue gt gt gt my_shape2 fill_color gree 1 n 1 my_shape2 fill_color gt gt gt print my_shape2 line_color blue green gt gt gt print my_shape2 line_color_ 0 0 0 2 50 1 0 Ar LG my_shape2 fill_color_ 0x 0p 140 This example shows how a mapped trait can be used to create a user friendly attribute such as line_color and a corresponding program friendly shadow attribute such as line_color_ The shadow attribute is program friendly because it is usually in a form that can b
102. e details of an object change as long as the same object is used Deprecated since version 3 0 3 Use comparison_mode instead traits traits password_editor auto_set True enter_set False Factory function that returns an editor for passwords traits traits multi_line text editor auto_set True enter_set False Factory function that returns a text editor for multi line strings traits traits code_editor Factory function that returns an editor that treats a multi line string as source code traits traits shell_editor Factory function that returns a Python shell for editing Python values traits traits time_editor Factory function that returns a Time editor for editing Time values traits traits date_editor Factory function that returns a Date editor for editing Date values traits traits trait_factory trait traits traits trait_cast something Casts a CTrait TraitFactory or TraitType to a CTrait but returns None if it is none of those traits traits try trait cast something Attempts to cast a value to a trait Returns either a trait or the original value 60 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 traits traits trait_from something Returns a trait derived from its input Private Classes class traits traits _InstanceArgs factory args kw class traits traits _TraitMaker value_type metadata adapter Module An extension to PyP
103. e if a Supports trait requires its values to implement interface Print able and an object is assigned to it which is of class Image which does not implement TPrintable then Traits looks for an adapter from Image to IPrintable and if one exists the adapter object is assigned to the trait If necessary a chain of adapter objects might be created in order to perform the required adaptation Main features The main features of the traits adaptation package are e Support for Python classes ABCs and traits Interfaces Protocols can be specified using any of those e Chaining of adapters Adapters can be chained i e an object can be adapted to a target protocol as long as there is a sequence of adapters that can be used to transform it e Conditional adaptation Adaptation of an object to a protocol can be conditional i e it may succeed or fail depending on the state of the object e Lazy loading The classes for the adapter the origin and the target protocols can be specified as strings and are only loaded if they are required 1 1 Traits 4 User Manual 39 Traits 4 User Manual Release 4 6 0 dev354 Note on terminology To avoid confusion let s define two terms that we will use all the time e We say that a class provides a protocol if it is a subclass of the protocol or if it implements the protocol if it is an interface e We say that a class supports a protocol if it provides the protocol or an adapter
104. e name def some_method self argl arg2 arg3 pass However the interpretation of arguments to these methods differs as shown in the following table Handler argument interpretation Argument _name_changed on_trait_change argl name object arg2 old name arg3 new new 4 For List and Dict trait attributes you can define a handler with the name _name_items_changed which receives notifications of changes to the contents of the list or dictionary This feature exists for backward compatibility The preferred approach is to use the on_trait_change decorator with extended name syntax For a static _name_items_changed handler the new parameter is a TraitListEvent or TraitDictEvent whose index added and removed attributes indicate the nature of the change and the o d parameter is Undefined 1 1 Traits 4 User Manual 19 Traits 4 User Manual Release 4 6 0 dev354 General Static Handler Signatures In the case of a non attribute specific handler the method signatures supported are _anytrait_changed _anytrait_changed name _anytrait_changed name new _anytrait_changed name old new The meanings for name new and old are the same as for attribute specific notification functions Trait Events The Traits package defines a special type of trait called an event Events are instances of subclasses of the Event class There are two major differences between a normal tr
105. e 4 6 0 dev354 As an alternative to implementing the validate method you can instead implement the is_valid_for method which receives only the value being assigned It should return True if the value is valid and False otherwise evalue_for self value As another alternative to implementing the validate method you can instead implement the value_for method which receives only the value being assigned It should return the validated form of value if it is valid or raise a TraitError if the value is not valid post_setattr self object name value This method allows the trait to do additional processing after value has been successfully assigned to the name trait of the object object For most traits there is no additional processing that needs to be done and this method need not be defined It is normally used for creating shadow i e mapped traits but other uses may arise as well This method does not need to return a value and should normally not raise any exceptions init Allows the trait to perform any additional initialization needed get default value Returns a tuple of the form default_value_type default_value which describes the default value for this trait The default implementation analyzes the value of the trait s default_value attribute and determines an appropriate default_value_type for default_value If you need to override this method to provide a different result tuple the follow
106. e 4 6 0 dev354 Predefined Transient Traits A number of the predefined traits in the Traits package are defined with transient set to True so you do not need to explicitly mark them The automatically transient traits are e Constant e Event e Read only and write only Property traits See Property Factory Function e Shadow attributes for mapped traits See Mapped Traits e Private attributes of HasPrivateTraits subclasses See HasPrivateTraits e Delegate traits that do not have a local value overriding the delegation Delegate traits with a local value are non transient i e they are serialized See DelegatesTo You can mark a Delegate trait as transient if you do not want its value to ever be serialized Overriding __getstate__ In general try to avoid overriding __ getstate__ in subclasses of HasTraits Instead mark traits that should not be pickled with transient True metadata However in cases where this strategy is insufficient use the following pattern to override __getstate__ to remove items that should not be persisted def _ getstate__ self state super XXX self __getstate__ for key in foo bar js if key in state del state key return state Unpickling HasTraits Objects The __setstate__ method of HasTraits differs from the default Python behavior in one important respect it explicitly sets the value of each attribute using the values from the state dictionary rathe
107. e directly used by program logic There are a few other points to keep in mind when creating a mapped trait e If not all values passed to the Trait function are dictionaries the non dictionary values are copied directly to the shadow attribute i e the mapping used is the identity mapping 1 1 Traits 4 User Manual 29 Traits 4 User Manual Release 4 6 0 dev354 e Assigning directly to a shadow attribute the attribute with the trailing underscore in the name is not allowed and raises a TraitError The concept of a mapped trait extends beyond traits defined via a dictionary Any trait that has a shadow value is a mapped trait For example for the Expression trait the assigned value must be a valid Python expression and the shadow value is the compiled form of the expression Trait Handlers In some cases you may want to define a customized trait that is unrelated to any predefined trait behavior or that is related to a predefined trait that happens to not be derived from TraitType The option for such cases is to use a trait handler either a predefined one or a custom one that you write A trait handler is an instance of the traits trait_handlers TraitHandler class or of a subclass whose task is to verify the correctness of values assigned to object traits When a value is assigned to an object trait that has a trait handler the trait handler s validate method checks the value and assigns that value or a computed
108. e inserted The default value is traits trait_types DictStrint lt traits trait_types Dict object gt Only a dictionary of string integer values can be assigned only string keys with integer values can be inserted The default value is traits trait_types DictStrLong lt traits trait_types Dict object gt Only a dictionary of string long integer values can be assigned only string keys with long integer values can be inserted The default value is traits trait_types DictStrFloat lt traits trait_types Dict object gt Only a dictionary of string float values can be assigned only string keys with float values can be inserted The default value is traits trait_types DictStrBool lt traits trait_types Dict object gt Only a dictionary of string bool values can be assigned only string keys with boolean values can be inserted The default value is traits trait_types DictStrList lt traits trait_types Dict object gt Only a dictionary of string list values can be assigned only string keys with list values can be assigned The default value is Private Classes class traits trait_types HandleWeakRef object name value Functions traits trait_types default_text_editor trait type None trait value Module Defines the TraitValue class used for creating special dynamic trait values 110 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 Classes class traits trait_
109. e object Matches object graphs where pattern occurs one or more times useful for setting up listeners on recursive data structures like trees or linked lists pattern Some examples of valid names and their meaning are as follows example meaning foo bar baz Listen for trait changes to object foo object bar and object baz foo bar Equivatent to foo bar baz but may be more useful in cases where the individual items are computed foo bar bag Listen for trait changes to object foo bar baz and report changes to object foo object foo bar or object foo bar baz foo bar baq4 Listen for changes to object foo bar baz and only report changes to object foo bar baz foo bar badlisten for trait changes to object foo bar and object foo baz left right Listeasfer trait changes to the name trait of each node of a tree having left and right links to other tree nodes and where object the method is applied to the root node of the tree dirty Listen for trait changes on any trait in the object which has the dirty metadata set foo dirty Listen for trait changes on any trait in object foo which has the dirty metadata set foo bar dilusten for trait changes on object foo bar or any trait on object foo which does not have dirty metadata set Note that any of the intermediate i e non final links in a pattern can be traits of type Ins
110. e that takes exactly one argument which is the object to be adapted known as the adaptee and returns an adapter from the from_protocol to the to_protocol The factory can be specified as either a callable or a string in the form foo bar baz which is turned into an import statement from foo bar import baz and imported when the trait is first accessed from_protocol Property Any Adapters created by the factory adapt from this protocol The protocol can be specified as a protocol class Interface or a string in the form foo bar baz which is turned into an import statement from foo bar import baz and imported when the trait is accessed 118 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 to_protocol Property Any Adapters created by the factory adapt to this protocol The protocol can be specified as a protocol class Interface or a string in the form foo bar baz which is turned into an import statement from foo bar import baz and imported when the trait is accessed adapter Module Base classes for adapters Adapters do not have to inherit from these classes as long as their constructor takes the object to be adapted as the first and only positional argument class traits adaptation adapter PurePythonAdapter adaptee Bases object Base class for pure Python adapters class traits adaptation adapter Adapter adaptee traits Bases traits has_traits
111. e value specified This is a useful shorthand when a number of trait attributes need to be set on an object or a trait attribute value needs to be set in a lambda function For example you can write 2 1 API Reference 65 Traits 4 User Manual Release 4 6 0 dev354 person trait_set name Bill age 27 instead of person name Bill person age 27 trait_setq traits Shortcut for setting object trait attributes Parameters traits Key value pairs the trait attributes and their values to be set No trait change notifications will be generated for any values assigned see also trait_set Returns self The method returns this object after setting attributes Description Treats each keyword argument to the method as the name of a trait attribute and sets the corresponding trait attribute to the value specified This is a useful shorthand when a number of trait attributes need to be set on an object or a trait attribute value needs to be set in a lambda function For example you can write person trait_setq name Bill age 27 instead of person name Bill person age 27 reset traits traits None metadata Resets some or all of an object s trait attributes to their default values Parameters traits list of strings Names of trait attributes to reset Returns unresetable list of strings A list of attributes that the method was unable to rese
112. eType weight Trait 0 0 TraitCoerceType float In this example the name attribute must be of type str string while the weight attribute must be of type float although both are based on instances of the TraitCoerceType class Note that this example is essentially the same as writing class Person HasTraits name Trait weight Trait 0 0 This simpler form is automatically changed by the Trait function into the first form based on TraitCoerceType instances when the trait attributes are defined For attributes based on TraitCoerceType instances if a value that is assigned is not of the type defined for the trait a TraitError exception is raised However in certain cases if the value can be coerced to the required type then the coerced value is assigned to the attribute Only widening coercions are allowed to avoid any possible loss of precision The following table lists the allowed coercions Trait Type Coercible Types complex float int float int long int unicode str class traits trait_handlers TraitCastType aType Ensures that a value assigned to a trait attribute is of a specified Python type or can be cast to the specified type This class is similar to TraitCoerceType but uses casting rather than coercion Values are cast by calling the type with the value to be assigned as an argument When casting is performed the result of the cast is the value assigned
113. ear with the number of deferral links that must be followed to find the default value for the trait e Getting an explicitly assigned value for a prototype No penalty i e standard Python attribute access speed or faster e Getting an explicitly assigned value for a delegate Cost of following the deferral chain e Setting Cost of following the deferral chain plus the cost of performing the validation of the new value The preceding discussions about deferral chain following and fast versus slow validation apply here as well In a typical application scenario where attributes are read more often than they are written and deferral is not used the impact of using traits is often minimal because the only cost occurs when attributes are assigned and validated The worst case scenario occurs when deferral is used heavily either for delegation or for prototyping to provide attributes with default values that are seldom changed In this case the cost of frequently following deferral chains may impose a measurable performance detriment on the application Of course this is offset by the convenience and flexibility provided by the deferral model As with any powerful tool it is best to understand its strengths and weaknesses and apply that understanding in determining when use of the tool is justified and appropriate 1 1 8 Testing Testing Traits Classes A mixin class is provided to facilitate writing tests for HasTraits classes The followin
114. ecause this attribute is defined using TraitPrefixList instances of Person have another attribute married_ whose default value is 1 the dictionary value corresponding to the key yes traits trait_handlers TraitPrefixMap map A cross between the TraitPrefixList and TraitMap classes Like TraitMap TraitPrefixMap is created using a dictionary but in this case the keys of the dictionary must be strings Like TraitPrefixList a string v is a valid value for the trait attribute if it is a prefix of one and only one key k in the dictionary The actual values assigned to the trait attribute is k and its corresponding mapped attribute is map k 2 1 API Reference 91 Traits 4 User Manual Release 4 6 0 dev354 Example mapping true 1 yes 1 false 0 no 0 boolean_map Trait true TraitPrefixMap mapping This example defines a Boolean trait that accepts any prefix of true yes false or no and maps them to 1 or 0 class traits trait_handlers TraitExpression Ensures that a value assigned to a trait attribute is a valid Python expression The compiled form of a valid expression is stored as the mapped value of the trait class traits trait_handlers TraitCompound handlers Provides a logical OR combination of other trait handlers This class provides a means of creating complex trait definitions by combining several simpler trait definitions TraitC
115. ect eset self object name value This is the setter method of a trait that behaves like a property Parameters object object The object that the property applies to name str The name of the property on object value The value being assigned as the value of the property Description If neither this method nor the get method is implemented the trait behaves like a normal trait attribute If this method is not defined but the get method is defined the trait behaves like a read only property This method does not need to return a value but it should raise a TraitError exception if the specified value is not valid and cannot be coerced or adapted to a valid value validate self object name value This method validates coerces or adapts the specified value as the value of the name trait of the object object This method is called when a value is assigned to an object trait that is based on this subclass of TraitType and the class does not contain a definition for either the get or set methods This method must return the original value or any suitably coerced or adapted value that is a legal value for the trait If value is not a legal value for the trait and cannot be coerced or adapted to a legal value the method should either raise a TraitError or call the error method to raise the TraitError on its behalf eis valid for self value 86 Chapter 2 Developer Reference Traits 4 User Manual Releas
116. ed_prop py Example of cached_property decorator from traits api import HasPrivateTraits List Int Property cached_property class TestScores HasPrivateTraits scores List Int average Property depends_on scores cached_property def _get_averag self s self scores return float reduce lambda nl n2 nl n2 s 0 len s The cached_property decorator takes no arguments Place it on the line preceding the property s getter method The depends_on metadata attribute accepts extended trait references using the same syntax as the on_trait_change method s name parameter described in The name Parameter As a result it can take values that specify attributes on referenced objects multiple attributes or attributes that are selected based on their metadata attributes Persistence In version 3 0 the Traits package provides __getstate__ and __setstate__ methods on HasTraits to implement traits aware policies for serialization and deserialization i e pickling and unpickling Pickling HasTraits Objects Often you may wish to control for a HasTraits subclass which parts of an instance s state are saved and which are discarded A typical approach is to define a __getstate__ method that copies the object s __dict__ attribute and deletes those items that should not be saved This approach works but can have drawbacks especially related to inheritance The HasTraits __ getsta
117. ef 7 wildard rules 34 wildcard examples 33 trait attribute names 33 wrapped_handler_ref traits traits_listener ListenerGroup attribute 113 wrapped_handler_ref traits traits_listener ListenerItem attribute 112 wrappers traits has_traits HasTraits attribute 63 X xgetattr in module traits trait_base 83 xsetattr in module traits trait_base 83 Index 145
118. eference to the view object If this attribute is not specified the View object returned by trait_view is used e parent toolkit control The reference to a user interface component to use as the parent window for the object s UI window e kind str The type of user interface window to create See the traitsui view kind_trait trait for values and their meanings If kind is unspecified or None the kind attribute of the View object is used e context object or dictionary A single object or a dictionary of string object pairs whose trait attributes are to be edited If not specified the current object is used e handler Handler A handler object used for event handling in the dialog box If None the default handler for Traits UI is used e id str A unique ID for persisting preferences about this user interface such as size and position If not specified no user preferences are saved e scrollable bool Indicates whether the dialog box should be scrollable When set to True scroll bars appear on the dialog box if it is not large enough to display all of the items in the view at one time Returns A UI object trait_context Returns the default context to use for editing or configuring traits 2 1 API Reference 67 Traits 4 User Manual Release 4 6 0 dev354 trait view name None view_element None Gets or sets a ViewElement associated with an object s class Parameters e name str
119. efinition They do not operate on trait attributes defined by way of wildcards or by calling add_trait For example gt gt gt class Person HasTraits name Str age Int oes temp_ Any gt gt gt bob Person gt gt gt bob temp_lunch sandwich gt gt gt bob add_trait favorite_sport Str football gt gt gt print bob trait names trait_added age name In this example the trait_names method returns only the age and name attributes defined on the Person class The trait_added attribute is an explicit trait event defined on the HasTraits class The wildcard attribute temp_lunch and the dynamically added trait attribute favorite_sport are not listed wrappers same TraitChangeNotify Wrapper extended ExtendedTraitChangeNotifyWrapper new NewTraitChangeNotify Wrapper fast ui FastUITraitChangeNotifyWrapper ui FastUITraitChangeNotify Wrapper Mapping from dispatch type to notification wrapper class type trait added Event basestring An event fired when a new trait is dynamically added to the object trait_modified Event An event that can be fired to indicate that the state of the object has been modified classmethod trait_monitor handler remove False Adds or removes the specified handler from the list of active monitors Parameters e handler function The function to add or remove as a monitor e remove bool Flag indicating wh
120. ems are of the specified trait type validate object name value Validates that the values is a valid list Note object can be None when validating a default value see e g clone full_info object name value Returns a description of the trait create editor Returns the default UI editor for the trait inner_traits Returns the inner trait or traits for this trait class traits trait_types CList trait None value None minlen 0 maxlen 9223372036854775807 items True metadata Defines a trait whose values must be a list whose items are of the specified trait type or which can be coerced to a list whose values are of the specified trait type validate object name value Validates that the values is a valid list full_info object name value Returns a description of the trait class traits trait_types Set trait None value None items True metadata Defines a trait whose value must be a set whose items are of the specified trait type validate object name value Validates that the values is a valid set Note object can be None when validating a default value see e g clone full_info object name value Returns a description of the trait 106 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 create editor Returns the default UI editor for the trait inner_traits Returns the inner trait or traits for this trait class trai
121. en debugging these errors the logging Logger exception only displays the tip of the traceback For example the following code changes a constant from traits api import HasTraits Int class Curmudgeon HasTraits constant Int 1 def _constant_changed self raise ValueError c Curmudgeon c constant 42 The constant trait change handler raises an exception that is caught and logged Exception occurred in traits notification handler Please check the log file for details Exception occurred in traits notification handler for object lt __main__ Curmudgeon object at 0x107603050 gt trait constant old value 0 new value 42 File curmudgeon py line 12 in _constant_changed raise ValueError ValueError This logged exception however only contains the tip of the traceback This makes debugging a bit difficult You can force exceptions to be re raised by adding a custom exception handler 1 1 Traits 4 User Manual 53 Traits 4 User Manual Release 4 6 0 dev354 from traits api import push_exception_handler push_exception_handler reraise_exceptions True For example you could add this to the top of the original code block Re running the original code example with this custom handler will now raise the following traceback Traceback most recent call last File curmudgeon py line 15 in lt module gt c constant 42 File curmudgeon py
122. er Manual Release 4 6 0 dev354 Notification Handler Signatures The handler passed to on_trait_change or on_trait_event can have any one of the following signatures e handler e handler new e handler name new handler object name new e handler object name old new These signatures use the following parameters e object The object whose trait attribute changed e name The attribute that changed If one of the objects in a sequence is a List or Dict and its membership changes then this is the name of the trait that references it with _items appended For example if the handler is monitoring foo bar baz where bar is a List and an item is added to bar then the value of the name parameter is bar_items e new The new value of the trait attribute that changed For changes to List and Dict objects this is a list of items that were added e old The old value of the trait attribute that changed For changes to List and Dict object this is a list of items that were deleted For event traits this is Undefined If the handler is a bound method it also implicitly has self as a first argument Dynamic Handler Special Cases In the one and two parameter signatures the handler does not receive enough information to distinguish between a change to the final trait attribute being monitored and a change to an intermediate object In this case the notification dispatcher attempts to map a change to an int
123. er classes custom 31 HandleWeakRef class in traits trait_handlers 90 HandleWeakRef class in traits trait_types 110 has_traits_interface traits has_traits HasTraits method 64 HasDynamicViews class in traits has_dynamic_views 82 HasPrivateTraits class in traits has_traits 78 HasPrivateTraits class 36 HasStrictTraits class in traits has_traits 78 HasStrictTraits class 35 HasTraits class in traits has_traits 63 HasTraits class 4 attribute methods 49 pickling 47 predefined subclasses 35 unpickling 48 HasUniqueStrings class in traits ustr_trait 116 HTML class in traits trait_types 101 id traits has_dynamic_views Dynamic View attribute 1 implements in module traits has_traits 79 import_object traits util trait_documenter TraitDocumenter method 128 import_symbol in module traits util import_symbol 127 importing Traits names 4 indent traits util event_tracer CallingMessageRecord at tribute 128 indent traits util event_tracer ChangeMessageRecord at tribute 128 traits util event_tracer ExitMessageRecord attribute 129 indent in module traits traits_listener 111 index traits traits_listener ListenerParser attribute 114 infoQ 26 info traits trait_handlers BaseTraitHandler method 85 info traits trait_numeric AbstractArray method 94 info traits trait_types BaseInstance method 107 info traits trait_types String method
124. erence The most general form of the Trait function is traits traits Trait default_value type constant value dictionary class function trait_handler trait The notation means a list of one or more of any of the items listed between the braces Thus this form of the function consists of a default value followed by one or more of several possible items A trait defined with multiple items is called a compound trait When more than one item is specified a trait value is considered valid if it meets the criteria of at least one of the items in the list The following is an example of a compound trait with multiple criteria compound py Example of multiple criteria in a trait definition from traits api import HasTraits Trait Range class Die HasTraits Define a compound trait definition value Trait 1 Range 1 6 Tone two three four five six The Die class has a value trait which has a default value of 1 and can have any of the following values e An integer in the range of 1 to 6 e One of the following strings one two three four five six Trait Parameters The items listed as possible arguments to the Trait function merit some further explanation e type See Type e constant value See Constant Value e dictionary See Mapped Traits e class Specifies that the trait value must be an instance of the specified c
125. ermediate object to its effective change on the final trait attribute This mapping is only possible if all the intermediate objects are single values such as Instance or Any traits and not List or Dict traits If the change involves a List or Dict then the notification dispatcher raises a TraitError when attempting to call a one or two parameter handler function because it cannot unambiguously resolve the effective value for the final trait attribute Zero parameter signature handlers receive special treatment if the final trait attribute is a List or Dict and if the string used for the name parameter is not just a simple trait name In this case the handler is automatically called when the membership of a final List or Dict trait is changed This behavior can be useful in cases where the handler needs to know only that some aspect of the final trait has changed For all other signatures the handler function must be explicitly set for the name_items trait in order to called when the membership of the name trait changes Note that the prefix and item syntaxes are both ways to specify both a trait name and its _items variant This behavior for zero parameter handlers is not triggered for simple trait names to preserve compatibility with code written for versions of Traits prior to 3 0 Earlier versions of Traits required handlers to be separately set for a trait and its items which would result in redundant notifications under the Traits
126. es e The object referenced by the trait named in the delegate parameter changes e The delegating attribute is explicitly changed Changes to the delegating attribute are propagated to the delegate object s attribute The prefix and listenable parameters to the initializer function specify additional information about how to do the delegation If prefix is the empty string or omitted the delegation is to an attribute of the delegate object with the same name as the trait defined by the DelegatesTo object Consider the following example delegate py Example of trait delegation from traits api import DelegatesTo HasTraits Instance Str class Parent HasTraits 5 Both of these class es inherit from the Delegate class Explicit use of Delegate is deprecated as its name and default behavior prototyping are incongruous 1 1 Traits 4 User Manual 21 Traits 4 User Manual Release 4 6 0 dev354 first_name Str last_name Str class Child HasTraits first_name Str last_name DelegatesTo father father Instance Parent mother Instance Parent noe gt gt gt tony Parent first_name Anthony last_name Jones gt gt gt alice Parent first_name Alice last_name Smith gt gt gt sally Child first_name Sally father tony mother alice gt gt gt print sally last_name Jones gt gt gt sally last_name Cooper Updates delegatee gt gt gt print tony
127. es not explicitly support old style classes Adaptation might work in particular cases but is not guaranteed to work correctly in situations involving old style classes When used with Traits the classes involved in adaptation are typically subclasses of HasTraits in which case this is not an issue The methods register_factory adapt etc use a global adaptation manager which is accessi ble through the function cet global adaptation manager The traits automatic adaptation fea tures also use the global manager Having a global adaptation manager can get you into trouble for the usual reasons related to having a global state If you want to have more control over adaptation we rec ommend creating a new AdaptationManager instance use it directly in your application and set it as the global manager using ser global adaptation manager A common issue with the global manager arises in unittesting where adapters registered in one test influence the outcome of other tests downstream Tests relying on adaptation should make sure to reset the state of the global adapter using reset global adaptation manager Recommended readings about adaptation This is a list of interesting readings about adaptation and the adapter pattern outside of Traits 1 1 Traits 4 User Manual 45 Traits 4 User Manual Release 4 6 0 dev354 e PyProtocols a precursor of traits adaptation e PEP 246 on object adaptation e Article about adapters in
128. ether to remove True or add the specified handler as a monitor for this class 2 1 API Reference 63 Traits 4 User Manual Release 4 6 0 dev354 Description If remove is omitted or False the specified handler is added to the list of active monitors if remove is True the handler is removed from the active monitor list classmethod add_class_trait name trait Adds a named trait attribute to this class Parameters e name str Name of the attribute to add e xtrait A trait or a value that can be converted to a trait using Trait Trait definition of the attribute It can be a single value or a list equivalent to an argument list for the Trait function classmethod add_trait_category category Adds a trait category to a class classmethod set_trait_dispatch_handler name klass override False Sets a trait notification dispatch handler classmethod trait_subclasses all False Returns a list of the immediate or all subclasses of this class Parameters all bool Indicates whether to return all subclasses of this class If False only immediate subclasses are returned has_traits_interface interfaces Returns whether the object implements a specified traits interface Parameters interfaces One or more traits Interface sub classes Description Tests whether the object implements one or more of the interfaces specified by interfaces Return True if it does and False otherwise trai
129. face or a list of interfaces Function traits interface_checker check_implements cls interfaces error_mode 0 Checks that the class implements the specified interfaces interfaces can be a single interface or a list of interfaces trait_base Module Defines common low level capabilities needed by the Traits package Classes traits trait_base Uninitialized lt uninitialized gt When the first reference to a trait is a get reference the default value of the trait is implicitly assigned and returned as the value of the trait Because of this implicit assignment a trait change notification is generated 82 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 with the Uninitialized object as the old value of the trait and the default trait value as the new value This allows other parts of the traits package to recognize the assignment as the implicit default value assignment and treat it specially traits trait_base Undefined lt undefined gt Singleton object that indicates that a trait attribute has not yet had a value set i e its value is undefined This object is used instead of None because None often has other meanings such as that a value is not used When a trait attribute is first assigned a value and its associated trait notification handlers are called Undefined is passed as the old parameter to indicate that the attribute previously had no value trait
130. fault lt undefined gt Returns the value of an extended object attribute name of the form name name2 name3 traits trait_base xsetattr object xname value Sets the value of an extended object attribute name of the form name name2 name3 traits trait_base is_none value traits trait_base not_none value traits trait_base not_false value traits trait_base not_event value traits trait_base is_str value 2 1 API Reference 83 Traits 4 User Manual Release 4 6 0 dev354 trait errors Module Defines the standard exceptions raised by the Traits package Functions traits trait_errors repr_type obj Return a string representation of a value and its type for readable error messages Classes class traits trait_errors TraitError args None name None info None value None class traits trait_errors TraitNotificationError class traits trait_errors DelegationError args trait handlers Module Defines the BaseTraitHandler class and a standard set of BaseTraitHandler subclasses for use with the Traits package A trait handler mediates the assignment of values to object traits It verifies via its validate method that a specified value is consistent with the object trait and generates a TraitError exception if it is not consistent Classes class traits trait_handlers BaseTraitHandler The task of this class and its subclasses is to verify the correctness of values assigned to object trait
131. fined elsewhere on the same class If a Property trait has only a getter function it acts as read only if it has only a setter function it acts as write only It can lack a function due to two situations e A function with the appropriate name is not defined on the class e The force option is True which requires the Property factory function to ignore functions on the class and one of the access functions was not specified in the arguments Caching a Property Value In some cases the cost of computing the value of a property trait attribute may be very high In such cases it is a good idea to cache the most recently computed value and to return it as the property value without recomputing it When a change occurs in one of the attributes on which the cached value depends the cache should be cleared and the property value should be recomputed the next time its value is requested One strategy to accomplish caching would be to use a private attribute for the cached value and notification lis tener methods on the attributes that are depended on However to simplify the situation Property traits support a cached_property decorator and depends_on metadata Use cached_property to indicate that a getter method s return value should be cached Use depends_on to indicate the other attributes that the property depends on For example 46 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 cach
132. g 6 custom trait handler 31 deferral 23 delegation 21 Disallow object 35 dynamic notification 13 events 20 handlers 16 interface definition 37 interface implementation 37 interface usage 38 list of values 9 metadata attributes 1 minimal 4 overriding default values 32 136 Index Traits 4 User Manual Release 4 6 0 dev354 per object trait attributes 36 prototype prefix 23 prototyping 23 registering adapters 40 static notification 18 subclassing traits 25 This trait 8 Trait function 27 TraitPrefixList class 30 TraitPrefixMap class 31 Traits features 2 transient metadata 47 wildcard 33 exception traits util event_tracer ExitMessageRecord at tribute 129 exceptions 53 ExitMessageRecord class in traits util event_tracer 128 explicit trait attribute definition 33 Expression class in traits trait_types 103 Expression 7 extended trait names examples 15 semantics 14 syntax 14 ExtendedTraitChangeNotify Wrapper traits trait_notifiers 115 class in F factory traits adaptation adaptation_offer AdaptationOffer attribute 118 File class in traits trait_types 103 File 7 find_resource in module traits util resource 126 Float class in traits trait_types 96 Float trait 5 float_validate traits trait_types BaseRange method 104 floating point number type 5 Font in module traits traits 58 Font 7 ForwardP
133. g doctest_tools 121 module document_members traits util trait_documenter TraitDocumenter method 127 dtype2trait in module traits trait_numeric 94 Dynamic View class in traits has_dynamic_views 81 DynamicViewSubElement class traits has_dynamic_views 81 in E edit_traits traits has_traits HasTraits method 67 editable_traits traits has_traits HasTraits method 69 editor metadata attribute 11 Either class in traits trait_types 109 Either 7 Enum class in traits trait_types 104 Enum 7 error traits trait_handlers BaseTraitHandler method 84 error traits traits_listener ListenerParser method 14 ETSConfig in module traits etsconfig etsconfig 120 evaluate traits trait_types BaseBool attribute 97 evaluate traits trait_types BaseCBool attribute 100 evaluate traits trait_types BaseCComplex attribute 99 evaluate traits trait_types BaseCFloat attribute 98 evaluate traits trait_types BaseCInt attribute 98 evaluate traits trait_types BaseCLong attribute 98 evaluate traits trait_types BaseComplex attribute 96 evaluate traits trait_types BaseFloat attribute 95 evaluate traits trait_types BaselInt attribute 95 evaluate traits trait_types BaseLong attribute 95 Event class in traits trait_types 108 Event 7 events 20 examples 20 example Adapter class 40 examples _any_trait_changed 18 add_class_trait 50 cached property 46 coercing vs castin
134. g methods are available when UnittestTools is added as a mixin class in the developer s test cases assertTraitChanges Assert an object trait changes a given number of times assertTraitDoesNotChange Assert an object trait does not change assertMultiTraitChanges Assert that traits on multiple objects do or do not change assertTraitChangesAsync Assert an object trait eventually changes assertEventuallyTrue Assert that the given condition is eventually true The above assert methods except assertEventuallyTrue can be used as context managers which at entry hook a trait listeners on the class for the desired events and record the arguments passed to the change handler at every fired event This way the developer can easily assert that specific events have been fired Further analysis and checking can be performed by inspecting the list of recorded events Both normal and extended trait names are supported However no check is performed regarding the validity of the trait name thus care is required to safeguard against spelling mistakes in the names of the traits that we need to assert the behaviour The following example demonstrates the basic usage of the mixin class in a TestCase import unittest from traits api import HasTraits Float List Bool on_trait_change from traits testing api import UnittestTools class MyClass HasTraits number Float 2 0 list_of_numbers List Float flag Bool on_tr
135. gister_offer in module traits adaptation adaptation_manager 118 register_offer traits adaptation adaptation_manager AdaptationManager method 117 register_provides in module traits adaptation adaptation_manager 118 register_provides traits adaptation adaptation_manager AdaptationManag method 117 registering adapters 40 remove_listener traits has_traits MetaHasTraits class method 62 remove_trait traits has_traits HasTraits method 76 repr traits trait_handlers BaseTraitHandler method 85 repr_type in module traits trait_errors 84 requesting adapters 42 reset_global_adaptation_manager in module traits adaptation adaptation_manager 118 reset_traits traits has_traits HasTraits method 66 resolve traits trait_types Type method 108 resolve_default_value traits trait_types Type method 108 traits adaptation adaptation_manager 118 reverse_assertion in module provides_protocol traits adaptation adaptation_manager AdaptationMantagesting unittest_tools 121 static method 117 RGBColor in module traits traits 58 Index 141 Traits 4 User Manual Release 4 6 0 dev354 RGBColor 7 rich compare metadata attribute 11 S supports_protocol in module traits adaptation adaptation_manager 118 supports_protocol traits adaptation adaptation_manager AdaptationMana method 117 save_to_directory traits util event_tracer MultiThreadRecow baldeass in
136. gs Dict of keyword value pairs to be passed to the cal lableObj Returns context context manager or None If callableObj is None an assertion context manager is returned inside of which a trait change trigger can be invoked Otherwise the context is used internally with cal lableOb 3 as the trigger in which case None is returned Note Checking if the provided trait corresponds to valid traits in the class is not implemented yet eUsing the functional version of the assert method requires the count argument to be given even if it is None assert TraitDoesNotChange obj trait callableObj None args kwargs Assert an object trait does not change Assert that the class trait does not change during execution of the provided function 122 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 Parameters e obj HasTraits The HasTraits class instance whose class trait will change e trait str The extended trait name of trait changes to listen to e callableObj callable optional A callable object that should not trigger a change in the passed trait When None default value a trigger is expected to be called under the context manger returned by this method e xargs List of positional arguments for cal lableOb 4 e xxkwargs Dict of keyword value pairs to be passed to the callableObj Returns context context manager or None If callableObj is None an as
137. hal 2014 03 21 14 11 20 781000 CALLING handle_list_items_special in C Users itziakos Projects t 2014 03 21 14 11 20 781000 gt list_of_numbers_items changed from to 3 0 in MyModel 2014 03 21 14 11 20 781000 CALLING _count_items in example py 2014 03 21 14 11 20 781000 lt EXIT count items EXCEPTION MyModel object has no attribute 2014 03 21 14 11 20 782000 lt EXIT handle_list_items_special 2014 03 21 14 11 20 782000 lt EXIT _add_number_to_list 1 2 Indices and tables e genindex e search 1 2 Indices and tables 55 Traits 4 User Manual Release 4 6 0 dev354 56 Chapter 1 User Reference CHAPTER 2 Developer Reference 2 1 API Reference 2 1 1 Traits core traits Module Defines the core traits for the Traits package A trait is a type definition that can be used for normal Python object attributes giving the attributes some additional characteristics Initialization Traits have predefined values that do not need to be explicitly initialized in the class constructor or elsewhere Validation Trait attributes have flexible type checked values Delegation Trait attributes values can be delegated to other objects Notification Trait attributes can automatically notify interested parties when their values change Visualization Trait attributes can automatically construct automatic or programmer defined user interfaces that allow their values to be edited or displ
138. has_dynamic_views DynamicView attribute 82 user_name_for in module traits trait_base 83 using traits 4 UStr class in traits ustr_trait 116 UUID class in traits trait_types 109 UUIDO 7 V validate 26 validate traits trait_handlers TraitHandler method 88 validate traits trait_numeric AbstractArray method 94 validate traits trait_types BaseBool method 97 validate traits trait_types BaseCBool method 100 validate traits trait_types BaseCComplex method 99 validate traits trait_types BaseCFloat method 98 validate traits trait_types BaseCInt method 98 validate traits trait_types BaseCLong method 98 validate traits trait_types BaseComplex method 96 validate traits trait_types BaseCStr method 99 validate traits trait_types BaseCUnicode method 99 validate traits trait_types BaseDirectory method 104 validate traits trait_types BaseEnum method 104 validate traits trait_types BaseFile method 103 validate traits trait_types BaseFloat method 96 validate traits trait_types BaseInstance method 107 validate traits trait_types BaseInt method 95 validate traits trait_types BaseLong method 95 validate traits trait_types BaseRange method 104 validate traits trait_types BaseStr method 96 validate traits trait_types BaseTuple method 105 validate traits trait_types BaseType method 101 validate traits trait_types BaseUnicode metho
139. have an initial value of None and are not type checked This feature is useful in cases where a class needs private attributes to keep track of its internal object state which are not part of the class s public API Such attributes do not need to be type checked because they are manipulated only by the presumably correct methods of the class itself class traits has_traits SingletonHasTraits Singleton class that support trait attributes class traits has_traits SingletonHasStrictTraits Singleton class that supports strict trait attributes Non trait attributes generate an exception class traits has_traits SingletonHasPrivateTraits Singleton class that supports trait attributes with private attributes being unchecked class traits has_traits Vetoable Defines a vetoable request object and an associated event class traits has_traits Interface The base class for all interfaces class traits has_traits ISerializable A class that implemented Serializable requires that all HasTraits objects saved as part of its state also implement ISerializable class traits has_traits traits_super ABC classes 78 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 Note These classes are only available when the abc module is present class traits has_traits ABCMetaHasTraits A MetaHasTraits subclass which also inherits from abc ABCMeta Note The ABCMeta class is cooperative and
140. he information passed to handler would be eobject object foo ename bar items eold Undefined enew TraitListEvent whose added trait contains the new item added to bar For signatures 2 and 3 the handler does not receive enough information to discern between a change to the final trait being listened to and a change to an intermediate link In this case the event dispatcher will attempt to map a change to an intermediate link to its effective change on the final trait This only works if all of the intermediate links are single values such as an Instance or Any trait and not Lists or Dicts If the modified intermediate trait or any subsequent intermediate trait preceding the final trait is a List or Dict then a TraitError is raised since the effective value for the final trait cannot in general be resolved unambiguously To prevent TraitErrors in this case use the separator to suppress notifications for changes to any of the intermediate links Handler signature also has the special characteristic that if a final trait is a List or Dict it will automat ically handle _items changed events for the final trait as well This can be useful in cases where the handler only needs to know that some aspect of the final trait has been changed For all other handler signatures you must explicitly specify the xxx_items trait if you want to be notified of changes to any of the items of the xxx trait sync_trait trait_na
141. he name of the trait that changed old The old value new The new value class_name The name of the class that the trait change took place class traits util event_tracer CallingMessageRecord time indent handler source Message record for a change handler call time Time stamp in UTC indent Depth level of the call in a chain of trait change dispatches handler The traits change handler that is called source The source file where the handler was defined 128 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 class traits util event_tracer ExitMessageRecord time indent handler exception Message record for returning from a change event dispatch time Time stamp in UTC indent Depth level of the exit in a chain of trait change dispatch handler The traits change handler that is called exception The exception type if one took place class traits util event_tracer RecordContainer A simple record container This class is commonly used to hold records from a single thread record record Add the record into the container save_to_file filename Save the records into a file class traits util event_tracer MultiThreadRecordContainer A container of record containers that are used by separate threads Each record container is mapped to a thread name id When a RecordContainer does not exist for a specific thread a new empty RecordContainer will be created on request
142. his framework create a dynamic view by registering a DynamicView declaration That declaration includes a name that forms the basis for the metadata attributes that are used to identify and order the desired view sub elements into the view s composition In addition the declaration includes any data to be passed into the constructor of the dynamic view and the id that should be used to persist the user s customization of the view Additionally this framework allows sub elements themselves to also be dynamically composed of further sub elements For example a dynamic view could be composed of two sub elements 1 The first is a dynamically composed HFlow which represents a toolbar that can be extended through contribu tions of toolbar buttons 2 The second could be a dynamic tabset where each page is also a contribution Programmers include dynamic sub elements within their dynamic views by contributing a DynamicViewSubElement into that view When the framework comes across this contribution while building the view it replaces that Dynam icViewSubElement with a fully initialized Traits ViewSubElement composed in a manner similar to how the elements of the View itself were composed Each contribution to a dynamic view or sub element must be an instance of a Traits ViewSubElement and must have associated metadata like the following for each dynamic view or sub element it will display in _ lt dynamic name order A float value The fra
143. hread If the current thread is the UI thread the notifications are executed immediately otherwise they are placed on the UI event queue fast Alias for ui new Run notifications in a new thread Description Multiple handlers can be defined for the same object or even for the same trait attribute on the same object If name is not specified or is None handler is invoked when any trait attribute on the object is changed The name parameter is a single xname or a list of xname names where an xname is an extended name of the form 70 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 xname2 xname2 An xname2 is of the form xname3 xname3 xname3 An xname3 is of the form xname name name name A name is any valid Python attribute name The semantic meaning of this notation is as follows expression meaning iteml item2 means item is a trait containing an object or objects if item is a list or dict with a trait called item2 Changes to either item or item2 cause a notification to be generated iteml item2 means item is a trait containing an object or objects if item is a list or dict with a trait called item2 Changes to item2 cause a notification to be generated while changes to item do not i e the indicates that changes to the link object sho
144. ignments should all work gt gt gt biill name William gt gt gt bill address 121 Drury Lane gt gt gt bill zip_code 55212 gt gt gt bill age 49 gt gt gt This should generate an error must be an Int gt gt gt bill age middle age Traceback most recent call last File all_wildcard py line 33 in lt module gt bill age middie age File c wrk src lib enthought traits trait_handlers py line 163 in error raise TraitError object name self info value TraitError The age trait of a Person instance must be an integer but a value of middle age lt type str gt was specified nun In this case all Person instance attributes can be created on the fly and are defined by the Any trait Wildcard Rules When using wildcard characters in trait attribute names the following rules are used to determine what trait definition governs an attribute 1 If an attribute name exactly matches a name without a wildcard character that definition applies 2 Otherwise if an attribute name matches one or more names with wildcard characters the definition with the longest name applies Note that all possible attribute names are covered by one of these two rules The base HasTraits class implicitly contains the attribute definition _ Python This rule guarantees that by default all attributes have standard Python language semantics These rules are demonstrated by the following example
145. imes the event should be fired e timeout float or None optional The amount of time in seconds to wait for the spec ified number of changes None can be used to indicate no timeout assertEventuallyTrue obj trait condition timeout 5 0 Assert that the given condition is eventually true Parameters e obj HasTraits The HasTraits class instance who s traits will change e trait str The extended trait name of trait changes to listen to 2 1 API Reference 123 Traits 4 User Manual Release 4 6 0 dev354 e condition callable A function that will be called when the specified trait changes This should accept obj and should return a Boolean indicating whether the condition is satisfied or not e timeout float or None optional The amount of time in seconds to wait for the con dition to become true None can be used to indicate no timeout assertDeprecated args kwds Assert that the code inside the with block is deprecated Intended for testing uses of traits util deprecated deprecated assertNotDeprecated args kwds Assert that the code inside the with block is not deprecated Intended for testing uses of traits util deprecated deprecated util Package util Package Utility functions part of the Traits project Copyright 2003 2013 Enthought Inc async_trait_wait Module traits util async_trait_wait wait_for_condition condition obj trait timeout None Wait until the given c
146. in traits trait_types 105 BaseType class in traits trait_types 101 BaseUnicode class in traits trait_types 97 Bool class in traits trait_types 98 128 in module traits util camel_case 124 CamelCaseToPython class in traits util camel_case 124 can document member traits util trait_documenter TraitDocumenter class method 127 CArray class in traits trait_numeric 94 CArray 7 casting types 5 6 Category class in traits category 62 CBool class in traits trait_types 100 CBool trait 5 CComplex class in traits trait_types 99 CComplex trait 5 CFloat class in traits trait_types 99 CFloat trait 5 Chaco 3 ChangeEventRecorder class in traits util event_tracer 129 ChangeMessageRecord class in traits util event_tracer 128 check_implements in module traits interface_checker 82 check_implements traits interface_checker InterfaceChecker method 82 Clnt class in traits trait_types 98 Clnt trait 5 Class class in traits trait_types 102 class parameter to Trait 27 ClassQ 7 class_default_traits_view traits has_traits HasTraits class method 68 class_editable_traits traits has_traits HasTraits class method 70 class_name traits util event_tracer ChangeMessageRecord attribute 128 class_of in module traits trait_base 83 134 Index Traits 4 User Manual Release 4 6 0 dev354 class_trait_names class method 78 class_trait_vie
147. ing values are valid values for default_value_type 0 1 The default_value item of the tuple is the default value e2 The object containing the trait is the default value 3 A new copy of the list specified by default_value is the default value 4 A new copy of the dictionary specified by default_value is the default value e5 A new instance of TraitListObject constructed using the default_value list is the default value A new instance of TraitDictObject constructed using the default_value dictionary is the default value 7 default_value is a tuple of the form callable args kw where callable is a callable args is a tuple and kw is either a dictionary or None The default value is the result obtained by invoking callable args kw 8 default_value is a callable The default value is the result obtained by invoking de fault_value object where object is the object containing the trait If the trait has a validate method the validate method is also called to validate the result 9 A new instance of TraitSetObject constructed using the default_value set is the default value clone default_value lt missing gt metadata Clones the contents of this object into a new instance of the same class and then modifies the cloned copy using the specified default_value and metadata Returns the cloned object as the result Note that subclasses can change the signature of this method if needed but sh
148. ion Note that the result can include information specific to the particular trait handler instance For example TraitRange instances return a string indicating the range of values acceptable to the handler e g an integer in the range from to 9 If the infoQ method is not overridden the default method returns the value of the info_text attribute repr value Returns a printable representation of a value along with its type Deprecated since version 3 0 3 This functionality was only used to provide readable error messages This functionality has been incorporated into TraitError itself Parameters value object The value to be printed get editor trait None Returns a trait editor that allows the user to modify the trait trait Parameters trait Trait The trait to be edited Description This method only needs to be specified if traits defined using this trait handler require a non default trait editor in trait user interfaces The default implementation of this method returns a trait editor that allows the user to type an arbitrary string as the value For more information on trait user interfaces refer to the Traits UI User Guide 2 1 API Reference 85 Traits 4 User Manual Release 4 6 0 dev354 create editor Returns the default traits UI editor to use for a trait inner traits Returns a tuple containing the inner traits for this trait Most trait handlers do not have any inner trai
149. ith a name based on the name of the trait attribute _name_default This method initializes the name trait attribute returning its initial value The method overrides any default value specified in the trait definition It is also possible to define a dynamic method for the default value in a trait type subclass get_default_value However using a _name_default method avoids the overhead of subclassing a trait Overriding Default Values in a Subclass Often a subclass must override a trait attribute in a parent class by providing a different default value You can specify a new default value without completely re specifying the trait definition for the attribute For example 32 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 override_default py Example of overriding a default value for a trait attribute in a subclass from traits api import HasTraits Range Str class Employee HasTraits name Str salary_grade Range value 1 low 1 high 10 class Manager Employee salary_grade 5 In this example the salary_grade of the Employee class is a range from 1 to 10 with a default value of 1 In the Manager subclass the default value of salary_grade is 5 but it is still a range as defined in the Employee class Reusing Trait Definitions As mentioned in Defining Traits Initialization and Validation in most cases traits are defined in line in attribute definitio
150. its traits 58 trait traits has_traits HasTraits method 76 Trait function examples 27 time 142 Index Traits 4 User Manual Release 4 6 0 dev354 trait_added traits has_traits HasTraits attribute 63 trait_cast in module traits traits 60 trait_context traits has_traits HasTraits method 67 trait_factory in module traits traits 60 trait_from in module traits traits 60 trait_get traits has_traits HasTraits method 64 trait_modified traits has_traits HasTraits attribute 63 trait_monitor traits has_traits HasTraits class method 63 trait_names traits has_traits HasTraits method 77 trait_set traits has_traits HasTraits method 65 trait_setq traits has_traits HasTraits method 66 trait_subclasses traits has_traits HasTraits method 64 trait_type metadata attribute 10 trait value metadata attribute 11 trait_view traits has_dynamic_views HasDynamic Views method 82 trait_view traits has_traits HasTraits method 68 trait_view_elements traits has_traits HasTraits method 68 trait_views traits has_traits HasTraits method 68 TraitCallable class in traits trait_handlers 92 TraitCastType class in traits trait_handlers 89 TraitChangeNotify Wrapper class in traits trait_notifiers 115 TraitClass class in traits trait_handlers 90 TraitCoerceType class in traits trait_handlers 89 TraitCompound class in traits trait_handlers 92
151. its_listener ListenerGroup attribute 113 notify traits traits_listener ListenerItem attribute 112 O object parameter notification handlers 16 traits adaptation adaptation_manager AdaptationManaggg date 26 static method 117 multi_line_text_editor in module traits traits 60 multiple values 9 MultiThreadChangeEventRecorder class in traits util event_tracer 129 MultiThreadRecordContainer class in traits util event_tracer 129 N name traits has_dynamic_views DynamicView at tribute 81 objtype traits util trait_documenter TraitDocumenter at tribute 127 traits util event_tracer ChangeMessageRecord attribute 128 old parameter to the notification handlers 16 on_trait_change decorator 17 method 13 semantics 18 syntax 17 on_trait_change 13 old name traits has_dynamic_views Dynamic ViewSubElementon_trait_change in module traits has_traits 80 attribute 81 name traits trait_value TraitValue attribute 111 name traits traits_listener ListenerlItem attribute 112 name traits traits_listener ListenerParser attribute 114 name traits util event_tracer ChangeMessageRecord at tribute 128 name parameter notification handlers 16 on_trait_change 14 on_trait_change traits has_traits HasTraits method 70 on_trait_event 13 method 13 on_trait_event traits has_traits HasTraits method 72 overriding default values examples 32 owner_deleted traits tr
152. ix trait based attributes with normal Python attributes or can opt to allow the use of only a fixed or open set of trait attributes within the class Trait attributes defined by a class are automatically inherited by any subclass derived from the class The following example illustrates each of the features of the Traits package These features are elaborated in the rest of this guide all_traits_features py Shows primary features of the Traits package from traits api import Delegate HasTraits Instance Int Str class Parent HasTraits INITIALIZATION last name is initialized to last_name Str class Child HasTraits 1 All code examples in this guide that include a file name are also available as examples in the tutorials doc_examples examples subdirectory of the Traits docs directory You can run them individually or view them in a tutorial program by running python lt Traits dir gt traits tutor tutor py lt Traits dir gt docs tutorials doc_examples 2 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 age Int VALIDATION father must be a Parent instance father Instance Parent DELEGATION last_name is delegated to father s last_name last_name Delegate father NOTIFICATION This method is called when age changes def _age_changed self old new print Age changed from s to 3s old new Set up
153. ject they are contained in or associated with Deferring leverages the common has a relationship between objects rather than the is a relationship that class inheritance provides There are two ways that a trait attribute can defer to another object s attribute delegation and prototyping In dele gation the deferring attribute is a complete reflection of the delegate attribute Both the value and validation of the delegate attribute are used for the deferring attribute changes to either one are reflected in both In prototyping the deferring attribute gets its value and validation from the prototype attribute until the deferring attribute is explicitly changed At that point while the deferring attribute still uses the prototype s validation the link between the values is broken and the two attributes can change independently This is essentially a copy on write scheme The concepts of delegation and prototyping are implemented in the Traits package by two classes derived from Trait Type DelegatesTo and PrototypedFrom gt DelegatesTo class DelegatesTo delegate prefix listenable True metadata The delegate parameter is a string that specifies the name of an attribute on the same object which refers to the object whose attribute is deferred to it is usually an Instance trait The value of the delegating attribute changes whenever e The value of the appropriate attribute on the delegate object chang
154. king up other listeners Since a common use case of deferring is to have a large number of deferred attributes for static object hierarchies this feature can be turned off by setting 1istenable False in order to speed up instantiation 1 1 Traits 4 User Manual 23 o allowance Traits 4 User Manual Release 4 6 0 dev354 Notification with Deferring While two trait attributes are linked by a deferring relationship either delegation or prototyping before the link is broken notifications for changes to those attributes are linked as well When the value of a deferred to attribute changes notification is sent to any handlers on the deferring object as well as on the deferred to object This behavior is new in Traits version 3 0 In previous versions only handlers for the deferred to object the object directly changed were notified This behavior is shown in the following example deferring_notification py Example of notification with deferring from traits api import HasTraits Instance PrototypedFrom Str class Parent HasTraits first_name SCE last_name Str def _last_name_changed self new print Parent s last name changed to s new class Child HasTraits father Instance Parent first_name Str last_name PrototypedFrom father def last name changed self new print Child s last name changed to ts new nnn gt gt gt dad Parent first_name William last
155. lass defines a new documenter that recovers the trait definition signature of module level and class level traits To use the documenter append the module path in the extension attribute of the conf py objtype traitattribute directivetype attribute member order 60 priority 12 classmethod can document member member membername isattr parent Check that the documented member is a trait instance 2 1 API Reference 127 Traits 4 User Manual Release 4 6 0 dev354 document members all_members False Trait attributes have no members add content more content no_docstring False Never try to get a docstring from the trait import object Get the Trait object Note Code adapted from autodoc Documenter import_object add_directive_header sig Add the directive header attribute with the annotation option set to the trait definition traits util trait_documenter setup app Add the TraitDocumenter in the current sphinx autodoc instance event_tracer Module Record trait change events in single and multi threaded environments class traits util event_tracer SentinelRecord Sentinel record to separate groups of chained change event dispatches class traits util event_tracer ChangeMessageRecord time indent name old new class_name Message record for a change event dispatch time Time stamp in UTC indent Depth level in a chain of trait change dispatches name T
156. lass or one of its subclasses e function A validator function that determines whether a value being assigned to the attribute is a legal value Traits version 3 0 provides a more flexible approach which is to subclass an existing trait or TraitType and override the validate method e trait_handler See Trait Handlers e trait Another trait object can be passed as a parameter any value that is valid for the specified trait is also valid for the trait referencing it 1 1 Traits 4 User Manual 27 Traits 4 User Manual Release 4 6 0 dev354 Type A type parameter to the Trait function can be any of the following standard Python types str or String Type unicode or UnicodeType int or IntType long or LongType float or FloatType complex or ComplexType bool or BooleanType list or ListType tuple or TupleType dict or DictType FunctionType MethodType ClassType InstanceType TypeType NoneType Specifying one of these types means that the trait value must be of the corresponding Python type Constant Value A constant_value parameter to the Trait function can be any constant belonging to one of the following standard Python types e NoneType e int e long e float e complex e bool e str e unicode Specifying a constant means that the trait can have the constant as a valid value Passing a list of constants to the Trait function is equivalent to using the Enum predefined trait
157. lidate self error object name value File c svn ets3 traits_3 0 3 enthought traits trait_handlers py line 175 in error value traits trait_errors TraitError The heads trait of an Alien instance must be one or two or three or any unique prefix but a value of t lt type str gt was specified 30 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 TraitPrefixMap The TraitPrefixMap handler combines the TraitPrefixList with mapped traits Its constructor takes a parameter that is a dictionary whose keys are strings A string is a valid value if it is a unique prefix for a key in the dictionary The value assigned is the dictionary value corresponding to the matched key The following example uses TraitPrefixMap to define a Boolean trait that accepts any prefix of true yes false or no and maps them to 1 or 0 traitprefixmap py Example of using the TraitPrefixMap handler from traits api import Trait TraitPrefixMap boolean_map Trait true TraitPrefixMap erete 1 yes 1 false 0 THOT Oo Custom Trait Handlers If you need a trait that cannot be defined using a predefined trait handler class you can create your own subclass of TraitHandler The constructor i e imit method for your TraitHandler subclass can accept whatever additional information if any is needed to completely specify the trait The constructor does
158. listeners for items reachable from this listener item be deferred until the associated trait is first read or set register new Registers new listeners unregister old Unregisters any existing listeners class traits traits_listener ListenerParser text traits Bases traits has_traits HasPrivateTraits len_text Int The length of the string being parsed index Int The current parse index within the string next Property The next character from the string being parsed name Property The next Python attribute name within the string skip_ws Property The next non whitespace character backspace Property Backspaces to the last character processed listener Instance ListenerBase The ListenerBase object resulting from parsing text text Str The string being parsed parse Parses the text and returns the appropriate collection of ListenerBase objects described by the text parse group ferminator Parses the contents of a group parse item terminator Parses a single complete listener item or group string parse metadata ire Parses the metadata portion of a listener item error msg Raises a syntax error classtraits traits listener ListenerNotifyWrapper handler owner id listener tar get None Bases traits trait_notifiers TraitChangeNotifyWrapper listener_deleted ref owner_deleted ref class traits traits_listener ListenerHandler handler Bases object
159. ll other cases the cached value _file_contents which maintained by the cached_property wrapper code is returned Note the use in the example of the depends_on metadata attribute to specify that the value of file_contents depends on file name so that get file contents is called only when file name changes For details see the traits traits Property function traits has_traits get_delegate_pattern name trait Returns the correct delegate listener pattern for a specified name and delegate trait traits has_traits implements interfaces Declares the interfaces that a class implements Parameters interfaces A list of interface classes that the containing class implements Description Registers each specified interface with the interface manager as an interface that the containing class implements Each specified interface must be a subclass of Interface This function should only be called from directly within a class body 2 1 API Reference 79 Traits 4 User Manual Release 4 6 0 dev354 Deprecated since version 4 4 Use the provides class decorator instead traits has_traits on_trait_change name post_init False names Marks the following method definition as being a handler for the extended trait change specified by name s Refer to the documentation for the on_trait_change method of the HasTraits class for information on the correct syntax for the name s argument A handler defined using
160. lse at application startup register_factory PersonToIName Person IName Adapter factories and conditional adaptation The first argument to the register factory function needs not be an adapter class it can be more generally an adapter factory An adapter factory can be any callable that accepts one positional argument the adaptee object and returns an adapter or None if the adaptation was not possible Adapter factories allow flexibility in the adaptation process as the result of adaptation may vary depending on the state of the adaptee object Conditional adaptation A common use of adapter factories is to allow adaptation only if the state of the adaptee object allows it The factory returns an adapter object if adaptation is possible or None if it is not In the following example a numpy ndarray object can be adapted to provide an IImage protocol only if the number of dimensions is 2 For illustration this example uses Python ABCs rather than Traits Interfaces import abc import numpy from traits api import Array HasTraits from traits adaptation api import adapt Adapter register_factory class ImageABC object __metaclass_ abc ABCMeta class NDArrayToImage Adapter adaptee Array Declare that NDArrayToImage implements ImageABC ImageABC register NDArrayToImage def ndarray_to_image_abc adaptee An adapter factory from numpy arrays to the ImageABC protocol if adaptee ndim ret
161. lue for the attribute Returns If the new value is valid this method must return either the original value passed to it or an alternate value to be assigned in place of the original value Whatever value this method returns is the actual value assigned to object name Description This method must be implemented by subclasses of TraitHandler It is called whenever a new value is assigned to a trait attribute defined using this trait handler If the value received by validate is not valid for the trait attribute the method must called the predefined error method to raise a TraitError exception class traits trait_handlers TraitRange low None high None exclude_low False ex clude_high False Ensures that a trait attribute lies within a specified numeric range TraitRange is the underlying handler for the predefined Range trait factory Any value assigned to a trait containing a TraitRange handler must be of the correct type and in the numeric range defined by the TraitRange instance No automatic coercion takes place For example class Person HasTraits age Trait 0 TraitRange 0 150 weight Trait 0 0 TraitRange 0 0 None This example defines a Person class which has an age trait attribute which must be an integer long in the range from 0 to 150 and a weight trait attribute which must be a non negative float value class traits trait_handlers TraitString minlen 0 maxlen 9223372036854775807 regex
162. lue for the trait traits trait_types ReadOnly traits trait_types Disallow class traits trait_types Constant value metadata Defines a trait whose value is a constant ctrait_type 7 Defines the CTrait type to use for this trait metadata transient True type constant The standard metadata for the trait class traits trait_types Delegate delegate prefix modify False listenable True meta data Defines a trait whose value is delegated to a trait on another object 102 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 ctrait_type 3 Defines the CTrait type to use for this trait metadata transient False type delegate The standard metadata for the trait as_ctrait Returns a CTrait corresponding to the trait defined by this class class traits trait_types DelegatesTo delegate prefix listenable True metadata Defines a trait delegate that matches the standard delegate design pattern class traits trait_types PrototypedF rom prototype prefix listenable True metadata Defines a trait delegate that matches the standard prototype design pattern class traits trait_types Expression default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be a valid Python expression The compiled form of a valid expression is stored as the mapped
163. me as the keyword This feature lets you associate metadata with a trait The following predefined keywords are accepted Keywords desc str Describes the intended meaning of the trait It is used in exception messages and fly over help in user interfaces label str Provides a human readable name for the trait It is used to label user interface editors for traits editor traits api Editor Instance of a subclass Editor object to use when creating a user interface editor for the trait See the Traits UI User Guide for more information on trait editors comparison_mode int Indicates when trait change notifications should be generated based upon the result of comparing the old and new values of a trait assignment e 0 NO_COMPARE The values are not compared and a trait change notification is generated on each assignment e 1 OBJECT_IDENTITY_COMPARE A trait change notification is generated if the old and new values are not the same object e 2 RICH_COMPARE A trait change notification is generated if the old and new values are not equal using Python s rich comparison operator This is the default rich_compare bool Indicates whether the basis for considering a trait attribute value to have changed is a rich comparison True the default or simple object identity False This attribute can be useful in cases where a detailed comparison of two objects is very expensive or where you do not care whether th
164. me object alias None mutual True remove False Synchronizes the value of a trait attribute on this object with a trait attribute on another object Parameters e name str Name of the trait attribute on this object e object object The object with which to synchronize e alias str Name of the trait attribute on other if None or omitted same as name e mutual bool or int Indicates whether synchronization is mutual True or non zero or one way False or zero e remove bool or int Indicates whether synchronization is being added False or zero or removed True or non zero 2 1 API Reference 75 Traits 4 User Manual Release 4 6 0 dev354 Description In mutual synchronization any change to the value of the specified trait attribute of either object results in the same value being assigned to the corresponding trait attribute of the other object In one way synchronization any change to the value of the attribute on this object causes the corresponding trait attribute of object to be updated but not vice versa add_trait name trait Adds a trait attribute to this object Parameters e name str Name of the attribute to add e xtrait Trait or a value that can be converted to a trait by Trait Trait definition for name If more than one value is specified it is equivalent to passing the entire list of values to Trait remove_trait name Removes a trait attribute from this obje
165. mework uses only ViewSubElements with this metadata instan tiated when building the dynamic view or sub element with the specified name The elements are sorted by ascending order of this value using the standard list sort function _ lt dynamic name gt _priority A float value The framework resolves any overloading of an order value by picking the first element encountered that has the highest priority value The other elements with the same view order are not displayed at all In addition dynamic view contributions can also provide a handler which behaves like a normal Traits Handler That is it can contain methods that are called when model values change and can access the Traits Ullnfo object representing the actual UI instances To provide a handler append the following metadata to your view sub element _ lt dynamic_name gt _handler A HasTraits instance The framework will connect listeners to call the handler meth ods as part of the handler for the dynamic view Classes class traits has_dynamic_views DynamicViewSubElement Declares a dynamic sub element of a dynamic view keywords Dict Keyword arguments passed in during construction of the actual ViewSubElement instance klass Any The class of the actual ViewSubElement we are dynamically creating name Str The name of this dynamic sub element This controls the metadata names identifying the sub elements that compose this element class traits has_dynamic_vie
166. must either raise a TraitError or calls the error method to raise a TraitError on its behalf The subclass can define a default value either as a constant or as a computed value To use a constant set the class level default_value attribute To compute the default value override the TraitType class s get_default_value method Defining a Trait Property A trait property uses get and set methods to interact with the value of the trait If a TraitType subclass contains a get method or a set method any definition it might have for validate is ignored The signatures of these methods are get object name set object name value In these signatures the parameters are e object The object that the property applies to e name The name of the trait property attribute on the object e value The value being assigned to the property If only a get method is defined the property behaves as read only If only a set method is defined the property behaves as write only The get method returns the value of the name property for the specified object The set method does not return a value but will raise a TraitError if the specified value is not valid and cannot be coerced or adapted to a valid value Other TraitType Members The following members can be specified for either a trait type or a trait property e info_text attribute or info method e init method e create editor method A trait must have an info
167. n 3 0 most predefined traits are defined as subclasses of traits trait_handlers TraitType As a result you can subclass one of these traits or TraitType to derive new traits Refer to the Traits API Reference to see whether a particular predefined trait derives from TraitType Here s an example of subclassing a predefined trait class trait_subclass py Example of subclassing a trait class from traits api import BaseInt class OddInt BaselInt Define the default value default_value 1 Describe the trait type info text an odd integer def validate self object name value value super OddInt self validate object name value if value 2 return value self error object name value The OddInt class defines a trait that must be an odd integer It derives from BaselInt rather than Int as you might initially expect Baselnt and Int are exactly the same except that Int has a fast_validate attribute which causes it to quickly check types at the C level not go through the expense of executing the general validate method As a subclass of BaseInt OddInt can reuse and change any part of the BaseInt class behavior that it needs to In this case it reuses the BaselInt class s validate method via the call to super in the OddInt validate method Further OddInt is related to BaseInt which can be useful as documentation and in programming You can use the subclassing strateg
168. n rewritten in v 4 4 0 See the migration guide below for details regarding changes in API Adaptation is the process of transforming an object that does not implement a specific interface needed by a client into an object that does In the adapter pattern an object is wrapped in a second object the adapter that implements the target interface Adaptation enables a programming style in which each component or service in an application defines an interface through which it would like to receive information Objects that need to communicate with the component declare an adapter for that interface as illustrated in the figure below 38 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 lmageToPrintable adapter Document DacumentTaPrintable adapter Printable protocol lmageTo2DArray adapter PrintingService Adaptation allows decoupling the data model from the application components and services introducing a new com ponent in the application should not require modifying the data objects Traits provides a package to make this pattern easy and automatic In the traits adaptation package adapters from a protocol type or interface to another can be registered with a manager object HasTraits classes can either explicitly request to adapt an object to a protocol or they can define special traits that automatically invoke the adaptation manager whenever it is necessary For exampl
169. name parameter can take any of the following values e Omitted None or anytrait The handler applies to any trait attribute on the object e A name or list of names The handler applies to each trait attribute on the object with the specified names e An extended name or list of extended names The handler applies to each trait attribute that matches the specified extended names Syntax Extended names use the following syntax xname xname2 xname2 x xname2 xname3 xname3 xname3 7 7 xname3 i xname name name name A name is any valid Python attribute name Semantics 14 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 Semantics of extended name notation Pattern Meaning item item2 A trait named item1 contains an object or objects if item is a list or dictionary with a trait named item2 Changes to either item or item2 trigger a notification item item2 A trait named item1 contains an object or objects if item is a list or dictionary with a trait named item2 Changes to item2 trigger a notification while changes to item do not i e the indicates that changes to the link object are not reported item item2 A list that matches any of the specified items Note that at the topmost level the surrounding data_name itemN square bracket
170. ne True adapt no mod ule Ensures that trait attribute values belong to a specified Python class or type TraitInstance is the underlying handler for the predefined trait Instance and the elements of List Instance Any trait that uses a TraitInstance handler ensures that its values belong to the specified type or class or one of its subclasses For example class Employee HasTraits manager Trait None TraitInstance Employee True This example defines a class Employee which has a manager trait attribute which accepts either None or an instance of Employee as its value TraitInstance ensures that assigned values are exactly of the type specified i e no coercion is performed class traits trait_handlers TraitWeakRef aClass allow_none True adapt no module class traits trait_handlers HandleWeakRef object name value class traits trait_handlers TraitClass aClass Ensures that trait attribute values are subclasses of a specified class or the class itself A value is valid if it is a subclass of the specified class including the class itself or it is a string that is equivalent to the name of a valid class class traits trait_handlers TraitFunction aFunc Ensures that assigned trait attribute values are acceptable to a specified validator function TraitFunction is the underlying handler for the predefined trait Function and for the use of function references
171. ngMessageRecord class in traits util event_tracer method 124 assertTraitChanges traits testing unittest_tools UnittestToelgmel_case_to_words method 122 assertTraitChangesAsync traits testing unittest_tools UnittestTools method 123 assert TraitDoesNotChange traits testing unittest_tools UnittestTools method 122 attribute definition 4 B backspace traits traits_listener ListenerParser attribute 114 base_trait traits has_traits HasTraits method 76 BaseBool class in traits trait_types 97 BaseCBool class in traits trait_types 100 BaseCComplex class in traits trait_types 99 BaseCFloat class in traits trait_types 98 BaseClInt class in traits trait_types 98 BaseClass class in traits trait_types 107 BaseCLong class in traits trait_types 98 BaseComplex class in traits trait_types 96 BaseCStr class in traits trait_types 99 BaseCUnicode class in traits trait_types 99 BaseDirectory class in traits trait_types 103 BaseEnum class in traits trait_types 104 BaseFile class in traits trait_types 103 BaseFloat class in traits trait_types 95 BaselInstance class in traits trait_types 107 Baselnt class in traits trait_types 95 BaseLong class in traits trait_types 95 BaseRange class in traits trait_types 104 BaseStr class in traits trait_types 96 BaseTraitHandler class in traits trait_handlers 84 BaseTraitValue class in traits trait_value 111 BaseTuple class
172. nges trigger the notification The name can specify complex patterns of trait changes using an extended name syntax which is described below e remove bool If True removes the previously set association between handler and name if False the default creates the association e dispatch str A string indicating the thread on which notifications must be run Pos sible values are value dispatch same Run notifications on the same thread as this one ui Run notifications on the UI thread If the current thread is the UI thread the notifications are executed immediately otherwise they are placed on the UI event gueue fast uAlias for ui new Run notifications in a new thread Description Multiple handlers can be defined for the same object or even for the same trait attribute on the same object If name is not specified or is None handler is invoked when any trait attribute on the object is changed The name parameter is a single xname or a list of xname names where an xname is an extended name of the form xname2 xname2 An xname2 is of the form xname3 xname3 xname3 amp x An xname3 is of the form xname name name Car ei name A name is any valid Python attribute name The semantic meaning of this notation is as follows 2 1 API Reference 73 Traits 4 User Manual Release 4 6 0 de
173. nicode validate object name value Validates that a specified value is valid for this trait Note The fast validator version performs this check in C 2 1 API Reference 99 Traits 4 User Manual Release 4 6 0 dev354 class traits trait_types CUnicode default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be a Python unicode string and which supports coercions of non unicode values to unicode using a C level fast validator fast_validate 12 lt type unicode gt The C level fast validator to use class traits trait_types BaseCBool default_value lt traits trait_handlers NoDefaultSpecified ob ject gt metadata Defines a trait whose value must be a Python boolean and which supports coercions of non boolean values to boolean evaluate The function to use for evaluating strings to this type alias of bool validate object name value Validates that a specified value is valid for this trait Note The fast validator version performs this check in C class traits trait_types CBool default_value lt traits trait_handlers NoDefaultSpecified objects metadata Defines a trait whose value must be a Python boolean and which supports coercions of non boolean values to boolean using a C level fast validator fast_validate 12 lt type bool gt The C level fast validator to use class traits trait_types
174. notifications are handled You can do this in two ways e Call the __setstate__ super method for example with an empty state dictionary e Call the HasTraits class s private _init_trait_listeners method this method has no parameters and does not return a result Useful Methods on HastTraits The HasTraits class defines a number of methods which are available to any class derived from it i e any class that uses trait attributes This section provides examples of a sampling of these methods Refer to the Traits API Reference for a complete list of HasTraits methods add_trait This method adds a trait attribute to an object dynamically after the object has been created For more information see Per Object Trait Attributes clone_traits This method copies trait attributes from one object to another It can copy specified attributes all explicitly defined trait attributes or all explicitly and implicitly defined trait attributes on the source object This method is useful if you want to allow a user to edit a clone of an object so that changes are made permanent only when the user commits them In such a case you might clone an object and its trait attributes allow the user to modify the clone and then re clone only the trait attributes back to the original object when the user commits changes set This method takes a list of keyword value pairs and sets the trait attribute corresponding to each keyword to the ma
175. ns but they can also be defined independently A trait definition only describes the characteristics of a trait and not the current value of a trait attribute so it can be used in the definition of any number of attributes For example trait_reuse py Example of reusing trait definitions from traits api import HasTraits Range coefficient Range 1 0 1 0 0 0 class quadratic HasTraits c2 coefficient cl coefficient c0 coefficient x Range 100 0 100 0 0 0 In this example a trait named coefficient is defined externally to the class quadratic which references coefficient in the definitions of its trait attributes c2 c1 and c0 Each of these attributes has a unique value but they all use the same trait definition to determine whether a value assigned to them is valid Trait Attribute Definition Strategies In the preceding examples in this guide all trait attribute definitions have bound a single object attribute to a specified trait definition This is known as explicit trait attribute definition The Traits package supports other strategies for defining trait attributes You can associate a category of attributes with a particular trait definition using the trait attribute name wildcard You can also dynamically create trait attributes that are specific to an instance using the add_trait method rather than defined on a class These strategies are described in the following sections Trait At
176. oDefaultSpecified objects metadata info text an object or a string of the form package package package module symbol arg1 argn specifyi A description of the type of value this trait accepts class traits trait_types UUID metadata Defines a trait whose value is a globally unique UUID type 4 info text a read only UUID A description of the type of value this trait accepts validate object name value Raises an error since no values can be assigned to the trait class traits trait_types WeakRef klass traits has_traits HasTraits allow_none False adapt yes metadata Returns a trait whose value must be an instance of the same type or a subclass of the specified klass which can be a class or an instance Note that the trait only maintains a weak reference to the assigned value traits trait_types Date lt traits trait_types BaseInstance object gt Defines a trait whose value must be an instance of a specified class or one of its subclasses traits trait_types Time lt traits trait_types BaseInstance object gt Defines a trait whose value must be an instance of a specified class or one of its subclasses traits trait_types ListInt lt traits trait_types List object gt List of integer values default value is traits trait_types ListFloat lt traits trait_types List object gt List of float values default value is traits trait_types ListStr lt traits tr
177. object foo bar baz foo bar baz Matches object foo bar and object foo baz foo Matches a list trait on object named foo left right Matches the name trait of each tree node object that is linked from the left or right traits of a parent node starting with the current object as the root node This pattern also matches the name trait of the current object as the left and right modifiers are optional t dirty Matches any trait on the current object that has a metadata attribute named dirty set foo tdirty Matches any trait on object foo that has a metadata attribute named dirty set foo bar adi r Matches object foo bar or any trait on object foo that does not have a metadata attribute named dirty set For a pattern that references multiple objects any of the intermediate non final links can be traits of type Instance List or Dict In the case of List or Dict traits the subsequent portion of the pattern is applied to each item in the list or value in the dictionary For example if self children is a list a handler set for children name listens for changes to the name trait for each item in the self children list The handler routine is also invoked when items are added or removed from a list or dictionary because this is treated as an implied change to the item s trait being monitored 1 1 Traits 4 User Manual 15 Traits 4 Us
178. odule traits trait_handlers 93 A ABCHasStrictTraits class in traits has_traits 79 ABCHasTraits class in traits has_traits 79 ABCMetaHasTraits class in traits has_traits 79 AbstractArray class in traits trait_numeric 94 active traits traits_listener ListenerlItem attribute 113 adapt in module traits adaptation adaptation_manager 118 adapt trats adaptation adaptation_manager AdaptationMap method 117 adaptation 38 adaptation_manager in module traits adaptation adaptation_manager 17 AdaptationError 116 AdaptationManager class in traits adaptation adaptation_manager 17 AdaptationOffer class in traits adaptation adaptation_offer 118 adaptee trait 40 Adapter class in traits adaptation adapter 119 Adapter class in traits adapter 61 Adapter class 40 example 40 adapters defining 40 registering 40 requesting 42 adapts in module traits adaptation adapter 119 adapts in module traits adapter 61 AdaptsTo class in traits trait_types 108 add_article in module traits trait_base 83 add_class_trait 49 examples 50 add_class_trait traits has_traits HasTraits method 64 add_content traits util trait_documenter TraitDocumenter method 128 add_directive_header traits util trait_documenter TraitDocumenter method 128 class add_listener _ traits has_traits MetaHasTraits class method 62 add_trait 36 49 add_trait traits has_traits HasTrait
179. ompound is the underlying handler for the general forms of the Trait function A value is a valid value for a trait attribute based on a TraitCompound instance if the value is valid for at least one of the TraitHandler or trait objects supplied to the constructor In addition if at least one of the TraitHandler or trait objects is mapped e g based on a TraitMap or TraitPrefixMap instance then the TraitCompound is also mapped In this case any non mapped traits or trait handlers use identity mapping class traits trait_handlers TraitTuple args Ensures that values assigned to a trait attribute are tuples of a specified length with elements that are of specified types TraitTuple is the underlying handler for the predefined trait Tuple and the trait factory Tuple Example rank Range l 13 suit Trait Hearts Diamonds Spades Clubs class Card HasTraits value Trait TraitTuple rank suit This example defines a Card class which has a value trait attribute which must be a tuple of two elments The first element must be an integer in the range from to 13 and the second element must be one of the four strings Hearts Diamonds Spades or Clubs class traits trait_handlers TraitCallable Ensures that the value of a trait attribute is a callable Python object usually a function or method class traits trait_handlers TraitListEvent index 0 removed None added None
180. ondition is true re evaluating on trait change This is intended for use in multithreading situations where traits can be modified from a different thread than the calling thread Wait until condition is satisfied Raise a RuntimeError if condition is not satisfied within the given timeout condition is a callback function that will be called with obj as its single argument It should return a boolean indicating whether the condition is satisfied or not timeout gives the maximum time in seconds to wait for the condition to become true The default value of None indicates no timeout obj trait give an object and trait to listen to for indication of a possible change whenever the trait changes the condition is re evaluated The condition will also be evaluated on entering this function Note that in cases of unusual timing it s possible for the condition to be evaluated one more time after the wait for condition call has returned camel case Module Defines utility functions for operating on camel case names classtraits util camel case CamelCaseToPython Simple functor class to convert names from camel case to idiomatic Python variable names For example gt gt gt camel2python CamelCaseToPython gt gt gt camel2python XMLActor2DToSGML xml_actor2d_to_sgml 124 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 traits util camel_case camel_case_to_words s Convert
181. or defining numpy based arrays validate object name value Validates that the value is a valid array info Returns descriptive information about the trait create editor Returns the default UI editor for the trait get default value Returns the default value constructor for the type called from the trait factory copy default value value co Returns a copy of the default value called from the C code on first reference to a trait with no current value I metadata Defines a trait whose value must be a numpy array traits trait_numeric ArrayOrNone args metadata I metadata Defines a trait whose value must be a numpy array with casting allowed Function traits trait_numeric dtype2trait dtype Get the corresponding trait for a numpy dtype trait_types Module Core Trait definitions Traits class traits trait_types Any default_value lt traits trait_handlers NoDefaultSpecified metadata Defines a trait whose value can be anything default_value None The default value for the trait info_text any value A description of the type of value this trait accepts class traits trait_types Generic default_value lt traits trait_handlers NoDefaultSpecified ject gt metadata A trait whose value may be either a NumPy array or None with casting allowed The default is None traits trait_numeric Array dtype None shape None value None typecode None
182. ould always call the super method if possible get_value object name trait None Returns the current value of a property based trait set_value object name value Sets the cached value of a property based trait and fires the appropriate trait change event API Reference 87 Traits 4 User Manual Release 4 6 0 dev354 as_ctrait Returns a CTrait corresponding to the trait defined by this class class traits trait_handlers TraitHandler The task of this class and its subclasses is to verify the correctness of values assigned to object trait attributes This class is an alternative to trait validator functions A trait handler has several advantages over a trait validator function due to being an object Trait handlers have constructors and state Therefore you can use them to create parametrized types Trait handlers can have multiple methods whereas validator functions can have only one callable interface This feature allows more flexibility in their implementation and allows them to handle a wider range of cases such as interactions with other components The only method of TraitHandler that must be implemented by subclasses is validate validate object name value Verifies whether a new value assigned to a trait attribute is valid Parameters e object object The object whose attribute is being assigned e name str The name of the attribute being assigned e value The proposed new va
183. pports coercions of non long values to long using a C level fast validator fast_validate 12 lt type long gt The C level fast validator to use class traits trait_types BaseCFloat default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be a Python float and which supports coercions of non float values to float evaluate The function to use for evaluating strings to this type alias of float 98 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 validate object name value Validates that a specified value is valid for this trait Note The fast validator version performs this check in C class traits trait_types CFloat default_value lt traits trait_handlers NoDefaultSpecified objects metadata Defines a trait whose value must be a Python float and which supports coercions of non float values to float using a C level fast validator fast_validate 12 lt type float gt The C level fast validator to use class traits trait_types BaseCComplex default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be a Python complex and which supports coercions of non complex values to complex evaluate The function to use for evaluating strings to this type alias of complex validate object name value Validates that a specified value is v
184. r in module traits traits 58 Color 7 Complex class in traits trait_types 96 complex number type 5 Complex trait 5 compound traits 27 configure_traits traits has_traits HasTraits method 69 Constant class in traits trait_types 102 Constant 7 constant_value parameter to Trait 27 28 copy traits trait_handlers TraitSetObject method 93 copy_default_value traits trait_numeric AbstractArray method 94 copy_traits traits has_traits HasTraits method 66 copyable_trait_names traits has_traits HasTraits method 66 create_editor 26 create_editor traits trait_handlers BaseTraitHandler method 85 create_editor method 94 create_editor traits trait_types BaseBool method 98 create_editor traits trait_types BaseComplex method 96 create_editor traits trait_types BaseEnum method 104 create_editor traits trait_types BaseFloat method 96 create_editor traits trait_types BaseInstance method 107 create_editor traits trait_types BaseInt method 95 create_editor traits trait_types BaseLong method 95 traits trait_numeric AbstractArray CTrait class in traits traits 57 ctrait_type traits trait_types Constant attribute 102 ctrait_type traits trait_types Delegate attribute 102 CUnicode class in traits trait_types 99 CUnicode trait 5 custom trait handler examples 31 custom traits 24 CyclicGraph 127 D Date in module traits trait_type
185. r than simply storing or copying the entire state dictionary to its ___dict__ attribute While slower this strategy has the advantage of generating trait change notifications for each attribute These notifications are important for classes that rely on them to ensure that their internal object state remains consistent and up to date Note If you re manually creating state dictionaries for consumption by __setstate__ you should be aware of an additional implementation detail when pickling the HasTraits __getstate__ method returns a dictionary with an extra traits version key giving the version of Traits used at pickling time If this key is not present when unpickling the HasTraits __setstate__ method falls back to a compatibility mode and may not restore the state correctly For the same reason if you re overriding __ getstate__ you should be careful to make the appropriate super self __getstate__ call Overriding __setstate__ You may wish to override the HasTraits __setstate__ method for example for classes that do not need to receive trait change notifications and where the overhead of explicitly setting each attribute is undesirable You can override __set 48 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 state__ to update the objects dict directly However in such cases it is important ensure that trait notifications are properly set up so that later change
186. rait_name is a specifier for one or more trait attributes using the syntax described in The name Parameter The signatures that are recognized for decorated handlers are the same as those for dynamic notification handlers as described in Notification Handler Signatures That is they can have an object parameter because they can handle notifications for trait attributes that do not belong to the same object Decorator Semantics The functionality provided by the on_trait_change decorator is identical to that of specially named handlers in that both result in a call to on_trait_change to register the method as a notification handler However the two approaches differ in when the call is made Specially named handlers are registered at class construction time decorated handlers are registered at instance creation time prior to setting any object state A consequence of this difference is that the on_trait_change decorator causes any default initializers for the traits it references to be executed at instance construction time In the case of specially named handlers any default initializers are executed lazily Specially named Notification Handlers There are two kinds of special method names that can be used for static trait attribute change notifications One is attribute specific and the other applies to all trait attributes on a class To notify about changes to a single trait attribute named name define a method named _name_
187. re single values such as an Instance or Any trait and not Lists or Dicts If the modified intermediate trait or any subsequent intermediate trait preceding the final trait is a List or Dict then a TraitError is raised since the effective value for the final trait cannot in general be resolved unambiguously To prevent TraitErrors in this case use the separator to suppress notifications for changes to any of the intermediate links Handler signature also has the special characteristic that if a final trait is a List or Dict it will automat ically handle _items changed events for the final trait as well This can be useful in cases where the handler only needs to know that some aspect of the final trait has been changed For all other handler signatures you must explicitly specify the xxx_items trait if you want to be notified of changes to any of the items of the xxx trait 72 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 on trait event handler name None remove False dispatch same priority False de ferred False target None Causes the object to invoke a handler whenever a trait attribute matching a specified pattern is modified or removes the association Parameters e handler function A trait notification function for the name trait attribute with one of the signatures described below e name str The name of the trait attribute whose value cha
188. rent object that should be GUI visible classmethod class visible traits Returns an alphabetically sorted list of the names of non event trait attributes associated with the current class that should be GUI visible print_traits show_help False metadata Prints the values of all explicitly defined non event trait attributes on the current object in an easily readable format Parameters show_help bool Indicates whether to display additional descriptive informa tion on trait change handler name None remove False dispatch same priority False de ferred False target None Causes the object to invoke a handler whenever a trait attribute matching a specified pattern is modified or removes the association Parameters e handler function A trait notification function for the name trait attribute with one of the signatures described below e name str The name of the trait attribute whose value changes trigger the notification The name can specify complex patterns of trait changes using an extended name syntax which is described below e remove bool If True removes the previously set association between handler and name if False the default creates the association e dispatch str A string indicating the thread on which notifications must be run Pos sible values are value dispatch same Run notifications on the same thread as this one ui Run notifications on the UI t
189. rface is returned When a situation like this arises the adapted object assigned to the trait always contains the smallest set of adapter objects needed to adapt the original object Also more specific adapters are preferred over less specific ones For example let s suppose we have a class Document and a subclass HTMLDocument We register two adapters to an interface Printable Document TolIPrintable and HTMLDocumentToIPrintable The call html_doc HTMLDocument printable adapt html_doc IPrintable will return an instance of the HTMLDocumentToIPrintable adapter as it is more specific than DocumentToIPrintable If no single adapter and no adapter chain can be constructed for the requested adaptation an AdaptationError is raised Alternatively one can specify a default value to be returned in this case printable adapt unprintable_doc IPrintable default EmptyPrintableDoc Using Traits interfaces An alternative syntax to create adapters when using Traits Interfaces is to use the interface class as an adapter factory for example printable IPrintable html_doc None is equivalent to printable adapt html_doc IPrintable default None the default argument None is optional 42 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 Using the Supports and AdaptsTo traits Using the terminology introduced in this section we can s
190. ribute If the value cannot be coerced to the required type a TraitError exception is raised Only widening coercions are allowed to avoid any possible loss of precision The following table lists traits that coerce values and the types that each coerces Type coercions permitted for coercing traits Trait Coercible Types Complex Floating point number plain integer Float Plain integer Long Plain integer Unicode String Trait Type Casting For trait attributes defined using the predefined casting traits if a value is assigned to a trait attribute that is not of the type defined for the trait but it can be cast to the required type then the cast value is assigned to the attribute If the value cannot be cast to the required type a TraitError exception is raised Internally casting is done using the Python built in functions for type conversion bool e complex e float e int e str e unicode The following example illustrates the difference between coercing traits and casting traits gt gt gt from traits api import HasTraits Float CFloat gt gt gt class Person HasTraits weight Float aes cweight CFloat gt gt gt gt gt gt bill Person gt gt gt bill weight 180 OK coerced to 180 0 gt gt gt bill cweight 180 OK cast to float 180 gt gt gt bill weight 180 Error invalid coercion Traceback most recent call last
191. rmation string that describes the values accepted by the trait type for example an odd integer Similarly to the default value the subclass s information string can be either a constant string or a computed string To use a constant set the class level info_text attribute To compute the info string override the TraitType class s info method which takes no parameters If there is type specific initialization that must be performed when the trait type is created you can override the init method This method is automatically called from the __init__ method of the TraitType class 26 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 If you want to specify a default TraitsUI editor for the new trait type you can override the create editor method This method has no parameters and returns the default trait editor to use for any instances of the type For complete details on the members that can be overridden refer to the Traits API Reference sections on the TraitType and BaseTraitHandler classes The Trait Factory Function The Trait function is a generic factory for trait definitions It has many forms many of which are redundant with the predefined shortcut traits For example the simplest form Trait default_value is equivalent to the functions for simple types described in Predefined Traits for Simple Types For the full variety of forms of the Trait function refer to the Traits API Ref
192. rojects where the Traits package has been used it has proven valuable for enhancing programmers ability to understand code during both concurrent development and maintenance The Traits 4 0 package works with version 2 7 and later of Python and is similar in some ways to the Python property language feature Standard Python properties provide the similar capabilities to the Traits package but with more work on the part of the programmer 1 1 3 Defining Traits Initialization and Validation Using the Traits package in a Python program involves the following steps 1 Import the names you need from the Traits package traits api 2 Define the traits you want to use 3 Define classes derived from HasTraits or a subclass of HasTraits with attributes that use the traits you have defined In practice steps 2 and 3 are often combined by defining traits in line in an attribute definition This strategy is used in many examples in this guide However you can also define traits independently and reuse the trait definitions across multiple classes and attributes see Reusing Trait Definitions In order to use trait attributes in a class the class must inherit from the HasTraits class in the Traits package or from a subclass of HasTraits The following example defines a class called Person that has a single trait attribute weight which is initialized to 150 0 and can only take floating point values minimal py Minimal example
193. roperty class in traits traits 58 from_protocol traits adaptation adaptation_offer AdaptationOffer attribute 118 full_infoQ traits trait_handlers BaseTraitHandler method 84 full info0 traits trait_types BaseEnum method 104 full info0 traits trait_types BaseRange method 104 full info0 traits trait_types BaseTuple method 105 full info0 traits trait_types CList method 106 full info0 traits trait_types CSet method 107 full info0 traits trait_types Dict method 107 full info0 traits trait_types Event method 109 full info0 traits trait_types List method 106 full info0 traits trait_types Set method 106 full info0 traits trait_types ValidatedTuple method 106 full info0 traits traits CTrait method 58 Function class in traits trait_types 101 function parameter to Trait 27 G factory traits adaptation cached_adapter_factory CachedAd p aehactotyss in traits trait_types 94 attribute 120 false 7 fast_validate traits trait_types Bool attribute 98 fast_validate traits trait_types CBool attribute 100 fast_validate traits trait_types CComplex attribute 99 fast_validate traits trait_types CFloat attribute 99 fast_validate traits trait_types CInt attribute 98 fast_validate traits trait_types Class attribute 102 fast_validate traits trait_types CLong attribute 98 fast_validate traits trait_types Complex attribute 96 fast_validate traits trait_types CStr attribute 9
194. rotocols to simplify the declaration of adapters Class class traits adapter Adapter args kw __init__ args kw Function traits adapter adapts args kw A class advisor for declaring adapters Parameters e from_ type or interface What the adapter adapts from or a list of such types or interfaces the _ suffix is used because from is a Python keyword e to type or interface What the adapter adapts fo or a list of such types or interfaces e factory callable An optional factory for actually creating the adapters This is any callable that takes a single argument which is the object to be adapted The factory should return an adapter if it can perform the adaptation and None if it cannot e cached bool Should the adapters be cached If an adapter is cached then the factory will produce at most one adapter per instance e when str A Python expression that selects which instances of a particular type can be adapted by this factory The expression is evaluated in a namespace that contains a single name adaptee which is bound to the object to be adapted e g adaptee is folder Note The cached and when arguments are ignored if factory is specified category Module Adds a category capability to Traits based classes similar to that provided by the Cocoa Objective C environment for the Macintosh You can use categories to extend an existing HasTrait
195. rs appear on the dialog box if it is not large enough to display all of the items in the view at one time Returns True on success Description This method is intended for use in applications that do not normally have a GUI Control does not resume in the calling application until the user closes the dialog box The method attempts to open and unpickle the contents of filename before displaying the dialog box When editing is complete the method attempts to pickle the updated contents of the object back to filename If the file referenced by filename does not exist the object is not modified before displaying the dialog box If filename is unspecified or None no pickling or unpickling occurs If edit is True the default a dialog box for editing the current object is displayed If edit is False or None no dialog box is displayed You can use edit False if you want the object to be restored from the contents of filename without being modified by the user 2 1 API Reference 69 Traits 4 User Manual Release 4 6 0 dev354 editable traits Returns an alphabetically sorted list of the names of non event trait attributes associated with the current object classmethod class_editable_traits Returns an alphabetically sorted list of the names of non event trait attributes associated with the current class visible traits Returns an alphabetically sorted list of the names of non event trait attributes associated with the cur
196. s print t trait foo is_trait_type Instance True print t trait foo is_trait_type List False print t trait any default flo 2 3 print t trait any default_kind list print t trait any inner_traits print t trait any is_trait_type Any True print t trait any is_trait_type List False 1 1 4 Trait Notification When the value of an attribute changes other parts of the program might need to be notified that the change has occurred The Traits package makes this possible for trait attributes This functionality lets you write programs using the same powerful event driven model that is used in writing user interfaces and for other problem domains Requesting trait attribute change notifications can be done in several ways 12 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 e Dynamically by calling on_trait_change or on_trait_event to establish or remove change notification han dlers e Statically by decorating methods on the class with the on_trait_change decorator to indicate that they handle notification for specified attributes e Statically by using a special naming convention for methods on the class to indicate that they handle notifications for specific trait attributes Dynamic Notification Dynamic notification is useful in cases where a notification handler cannot be defined on the class or a subclass whose trait
197. s traits adaptation adaptation_manager no_adapter_necessary adaptee An adapter factory used to register that a protocol provides another See register_provides for details class traits adaptation adaptation_manager AdaptationManager Bases traits has_traits HasTraits Manages all registered adaptations static mro_distance_to_protocol from_type to_protocol Return the distance in the MRO from from_type to to_protocol If from_type provides to_protocol returns the distance between from_type and the super most class in the MRO hierarchy providing to_protocol that s where the protocol was provided in the first place If from_type does not provide to_protocol return None static provides_protocol type_ protocol Does the given type provide i e implement a given protocol Parameters e type Python type e protocol Either a regular Python class or a traits Interface Returns result bool True if the object provides the protocol otherwise False adapt adaptee to_protocol default lt class traits adaptation adaptation_error AdaptationError gt Attempt to adapt an object to a given protocol Parameters e adaptee The object that we want to adapt e to_protocol The protocol that the want to adapt the object to If adaptee already provides i e implements the given protocol then it is simply returned unchanged Otherwise we try to build a chain of adapters that adapt a
198. s 109 date_editor in module traits traits 60 debugging 53 declare_dynamic_view traits has_dynamic_views HasDynamic Views method 82 decorator on_trait_change 17 Default class in traits traits 58 default traits trait_value TraitValue attribute 111 default metadata attribute 10 default value method 32 overriding in a subclass 32 default_kind metadata attribute 10 default_text_editor in module traits trait_types 110 default traits view0 traits has_traits HasTraits method 68 default_value traits trait_types Any attribute 94 default_value traits trait_types BaseBool attribute 97 default_value traits trait_types BaseComplex attribute 96 default_value traits trait_types BaseFloat attribute 96 default_value traits trait_types BaseInt attribute 95 default_value traits trait_types BaseLong attribute 95 default_value traits trait_types BaseStr attribute 96 Index 135 Traits 4 User Manual Release 4 6 0 dev354 default_value traits trait_types BaseUnicode attribute 97 default_value traits trait_types Callable attribute 101 default_value traits trait_types Expression attribute 103 default_value traits trait_types Python attribute 102 default_value attribute 25 default_value_type traits trait_types self attribute 101 Default Value in module traits trait_value 111 deferral 2 21 examples 23 notification with 23 deferred traits traits_listener ListenerGroup attribu
199. s Shortcut for setting object trait attributes Parameters e trait_change_notify bool If True the default then each value assigned may generate a trait change notification If False then no trait change notifications will be generated see also trait_setq e xxtraits Key value pairs the trait attributes and their values to be set Returns self The method returns this object after setting attributes Description Treats each keyword argument to the method as the name of a trait attribute and sets the corresponding trait attribute to the value specified This is a useful shorthand when a number of trait attributes need to be set on an object or a trait attribute value needs to be set in a lambda function For example you can write person trait_set name Bill age 27 instead of person name Bill person age 27 set args kw Shortcut for setting object trait attributes Parameters e trait_change_notify bool If True the default then each value assigned may generate a trait change notification If False then no trait change notifications will be generated see also trait_setq e x traits Key value pairs the trait attributes and their values to be set Returns self The method returns this object after setting attributes Description Treats each keyword argument to the method as the name of a trait attribute and sets the corresponding trait attribute to th
200. s are optional item A trait named item is a list Changes to item or to its members triggers a notification name If the current object does not have an attribute called name the reference can be ignored If the character is omitted the current object must have a trait called name otherwise an exception is raised prefixt Matches any trait attribute on the object whose name begins with prefix meta Matches any trait on the object that has a metadata attribute called metadata_name metadata_nam Matches any trait on the current object that does not have a metadata attribute called metadata_name pre jixt metadata_nanwalled metadata name Matches any trait on the object whose name begins with prefix and that has a metadata attribute prefix metadata_nam Matches any trait on the object whose name begins with prefix and that does not have a metadata attribute called metadata_name Matches all traits on the object pattern Matches object graphs where pattern occurs one or more times This option is useful for setting up listeners on recursive data structures like trees or linked lists Examples of extended name notation Example Meaning foo bar Matches object foo object bar and object baz baz l foo Equivalent to foo bar baz but may be useful in cases where the individual items bar are computed baz foo bar baz Matches
201. s class as an alternative to subclassing An advantage of cate gories over subclassing is that you can access the added members on instances of the original class without having to change them to instances of a subclass Unlike subclassing categories do not allow overriding trait attributes 2 1 API Reference 61 Traits 4 User Manual Release 4 6 0 dev354 Classes class traits category MetaCategory class traits category MetaCategoryOb ject cls class_name bases class_dict is category class traits category Category Used for defining category extensions to existing classes To define a class as a category specify Category followed by the name of the base class name in the base class list The following example demonstrates defining a category from traits api import HasTraits Str Category class Base HasTraits x Str Base x y Str Base y class BaseExtra Category Base z Str BaseExtra z has_traits Module Defines the HasTraits class along with several useful subclasses and associated metaclasses Classes class traits has_traits ViewElement class traits has_traits MetaHasTraits classmethod add_listener listener class_name Adds a class creation listener If the class name is the empty string then the listener will be called when any class is created classmethod remove_listener listener class_name Removes a class creation listener clas
202. s method 76 add_trait_category traits has_traits HasTraits class method 64 add_traits_meta_data traits has_traits MetaHasTraitsObject method 63 all_trait_names traits has_traits HasTraits method 66 a i in traits trait_types 94 oT args traits trait_value TraitValue attribute 111 Array class in traits trait_numeric 94 array metadata attribute 10 Array 7 ArrayOrNone class in traits trait_numeric 94 133 Traits 4 User Manual Release 4 6 0 dev354 as_ctrait traits trait_handlers TraitType method 87 as_ctrait traits trait_types Delegate method 103 as_ctrait traits trait_types Either method 109 as_ctrait traits trait_types Expression method 103 as_ctrait traits trait_types Supports method 108 as_ctrait traits trait_value BaseTrait Value method 111 Bool trait 5 Boolean type 5 Button class in traits trait_types 109 Button 7 C assertDeprecated traits testing unittest_tools UnittestToolyached_property decorator 46 method 124 assertEventuallyTrue traits testing unittest_tools Unittest TogbpedAdapterFactory method 123 assertMultiTraitChanges traits testing unittest_tools UnittestTools method 123 cached_property in module traits has_traits 79 class in traits adaptation cached_adapter_factory 119 Callable class in traits trait_types 101 CallableQ 7 assertNotDeprecated traits testing unittest_tools UnittestToglsi
203. s to object foo bar baz and report changes to object foo object foo bar or object foo bar baz foo bar baq4 Listen for changes to object foo bar baz and only report changes to object foo bar baz foo bar badlisten for trait changes to object foo bar and object foo baz left right Listeasfer trait changes to the name trait of each node of a tree having left and right links to other tree nodes and where object the method is applied to the root node of the tree dirty Listen for trait changes on any trait in the object which has the dirty metadata set foo dirty Listen for trait changes on any trait in object foo which has the dirty metadata set foo bar dilusten for trait changes on object foo bar or any trait on object foo which does not have dirty metadata set 2 1 API Reference 71 Traits 4 User Manual Release 4 6 0 dev354 Note that any of the intermediate i e non final links in a pattern can be traits of type Instance List or Dict In the case of List and Dict traits the subsequent portion of the pattern is applied to each item in the list or value in the dictionary For example if the self children is a list children name listens for trait changes to the name trait for each item in the self children list Note that items added to or removed from a list or dictionary in the pattern will cause the handler routine to be invoked as well
204. s trait_base Missing lt missing gt Singleton object that indicates that a method argument is missing from a type checked method signature traits trait_base Self lt self gt Singleton object that references the current object Functions traits trait_base strx arg Wraps the built in str function to raise a TypeError if the argument is not of a type in StringTypes traits trait_base class_of object Returns a string containing the class name of an object with the correct indefinite article a or an preceding it e g an Image a PlotValue traits trait_base add_article name Returns a string containing the correct indefinite article a or an prefixed to the specified string traits trait_base user_name_for name Returns a user friendly version of a string with the first letter capitalized and with underscore characters replaced by spaces For example user name for user name for returns User name for traits trait_base traits_home Gets the path to the Traits home directory traits trait_base verify_path path Verify that a specified path exists and try to create it if it does not exist traits trait_base get_module_name level 2 Returns the name of the module that the caller s caller is located in traits trait_base get_resource_path evel 2 Returns a resource path calculated from the caller s stack traits trait_base xgetattr object xname de
205. s traits has_traits MetaInterface Meta class for interfaces Interfaces are simple ABCs with the following features 1 They cannot be instantiated they are interfaces not implementations 2 Calling them is equivalent to calling adapt init_ X __init__ initializes x see help type x for signature call ares kw Attempt to adapt the adaptee to this interface Note that this means that intentionally that interfaces cannot be instantiated 62 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 class traits has_traits MetaHasTraitsObject cls class_name bases class_dict is_category Performs all of the meta class processing needed to convert any subclass of HasTraits into a well formed traits class __init__ cls class_name bases class_dict is category Processes all of the traits related data in the class dictionary add traits meta data bases class dict base traits class traits instance traits prefix_traits listeners view elements Adds the Traits metadata to the class dictionary migrate property name property property info class dict Migrates an existing property to the class being defined allowing for method overrides class traits has_traits HasTraits Enables any Python class derived from it to have trait attributes Most of the methods of HasTraits operated by default only on the trait attributes explicitly defined in the class d
206. sed for resolving local class names e g LocalClass This is an abstract class that only provides helper methods used to resolve the class name into an actual class object class traits trait_types BaseInstance klass None factory None args None kw None al low_none True adapt None module None meta data Defines a trait whose value must be an instance of a specified class or one of its subclasses validate object name value Validates that the value is a valid object instance info Returns a description of the trait get_default_value Returns a tuple of the form default_value_type default_value which describes the default value for this trait 2 1 API Reference 107 Traits 4 User Manual Release 4 6 0 dev354 create editor Returns the default traits UI editor for this type of trait init_fast_validate Does nothing for the BaseInstance class Used by the Instance AdaptedTo and AdaptsTo classes to set up the C level fast validator class traits trait_types Instance klass None factory None args None kw None al low_none True adapt None module None metadata Defines a trait whose value must be an instance of a specified class or one of its subclasses using a C level fast validator init_fast_validate Sets up the C level fast validator class traits trait_types Supports klass None factory None args None kw None al low_none True adapt
207. ser Manual 35 Traits 4 User Manual Release 4 6 0 dev354 Attempting to set other types of values generates an exception as does attempting to set an attribute that is not one of the three defined attributes In essence TreeNode behaves like a type checked data structure HasPrivateTraits This class is similar to HasStrictTraits but allows attributes beginning with _ to have an initial value of None and to not be type checked This is useful in cases where a class needs private attributes which are not part of the class s public API to keep track of internal object state Such attributes do not need to be type checked because they are only manipulated by the presumably correct methods of the class itself The definition of HasPrivateTraits is the following class HasPrivateTraits HasTraits Any Disallow These subclasses of HasTraits are provided as a convenience and their use is completely optional However they do illustrate how easy it is to create subclasses with customized default attribute behavior if desired Per Object Trait Attributes The Traits package allows you to define dynamic trait attributes that are object rather than class specific This is accomplished using the add_trait method of the HasTraits class add_trait name trait For example object_trait_attrs py Example of per object trait attributes from traits api import HasTraits Range class GUI
208. sertion context manager is returned inside of which a trait change trigger can be invoked Otherwise the context is used internally with cal lableOb j as the trigger in which case None is returned assertMultiTraitChanges objects traits_modified traits not modified Assert that traits on multiple objects do or do not change This combines some of the functionality of assertTraitChanges and assertTraitDoesNotChange Parameters e objects list of HasTraits The HasTraits class instances whose traits will change e traits_modified list of str The extended trait names of trait expected to change e traits_not_modified list of str The extended trait names of traits not expected to change assertTraitChangesAsync args kwds Assert an object trait eventually changes Context manager used to assert that the given trait changes at least count times within the given timeout as a result of execution of the body of the corresponding with block The trait changes are permitted to occur asynchronously Example usage with self assertTraitChangesAsync my_object SomeEvent count 4 lt do stuff that should cause my_object SomeEvent to be fired at least 4 times within the next 5 seconds gt Parameters e obj HasTraits The HasTraits class instance whose class trait will change e trait str The extended trait name of trait changes to listen to e count int optional The expected number of t
209. since this is treated as an implied change to the item s trait being monitored The signature of the handler supplied also has an effect on how changes to intermediate traits are pro cessed The five valid handler signatures are 1 handler 2 handler new 3 handler name new 4 handler object name new 5 handler object name old new For signatures 1 4 and 5 any change to any element of a path being listened to invokes the handler with in formation about the particular element that was modified e g if the item being monitored is foo bar baz a change to bar will call handler with the following information eobject object foo ename bar eold old value for object foo bar enew new value for object foo bar If one of the intermediate links is a List or Dict the call to handler may report an _items changed event If in the previous example bar is a List and a new item is added to bar then the information passed to handler would be eobject object foo ename bar items eold Undefined enew TraitListEvent whose added trait contains the new item added to bar For signatures 2 and 3 the handler does not receive enough information to discern between a change to the final trait being listened to and a change to an intermediate link In this case the event dispatcher will attempt to map a change to an intermediate link to its effective change on the final trait This only works if all of the intermediate links a
210. sm for dynamically modifying trait definitions See the Traits API Reference for details on TraitValue If trait_value is True then setting the trait attribute to Trait Value with no arguments resets the attribute to it original default value transient A Boolean indicating that the trait value is not persisted when the object containing it is persisted The default value for most predefined traits is False the value will be persisted if its container is You can set it to True for traits whose values you know you do not want to persist Do not set it to True on traits where it is set internally to False as doing so is likely to create unintended consequences See Persistence for more information Other metadata attributes may be recognized by specific predefined traits Accessing Metadata Attributes Here is an example of setting trait metadata using keyword arguments keywords py Example of trait keywords from traits api import HasTraits Str class Person HasTraits first name Str desc first or personal name label First Name last name Str desc last or family name label Last Name 1 1 Traits 4 User Manual 11 Traits 4 User Manual Release 4 6 0 dev354 In this example in a user interface editor for a Person object the labels First Name and Last Name would be used for entry fields corresponding to the first_name and last_name trait attributes If the user
211. st of strings A list of attributes that the method was unable to copy which is empty if all the attributes were successfully copied clone_traits traits None memo None copy None metadata Clones a new object from this one optionally copying only a specified set of traits Parameters e traits list of strings The list of names of the trait attributes to copy e memo dict A dictionary of objects that have already been copied e copy str The type of copy deep or shallow to perform on any trait that does not have explicit copy metadata A value of None means copy reference Returns new The newly cloned object Description Creates a new object that is a clone of the current object If traits is None the default then all explicit trait attributes defined for this object are cloned If traits is all or an empty list the list of traits returned by all_trait_names is used otherwise traits must be a list of the names of the trait attributes to be cloned edit traits view None parent None kind None context None handler None id scrol lable None args Displays a user interface window for editing trait attribute values Parameters e view View or string A View object or its name that defines a user interface for editing trait attribute values of the current object If the view is defined as an attribute on this class use the name of the attribute Otherwise use a r
212. stened to traits is changed type Enum ANY_LISTENER SRC_LISTENER DST_LISTENER The type of handler being used notify Bool True Should changes to this item generate a notification to the handler deferred Bool False Should registering listeners for items reachable from this listener item be deferred until the associated trait is first read or set is any trait Bool False Is this an any_trait change listener or does it create explicit listeners for each individual trait 112 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 is list handler Bool False Is the associated handler a special list handler that handles both foo and foo_items events by receiving a list of deleted and added items as the old and new arguments active Instance WeakKeyDictionary A dictionary mapping objects to a list of all current active name type listener pairs where type defines the type of listener one of SIMPLE_LISTENER LIST_LISTENER DICT_LISTENER register new Registers new listeners unregister old Unregisters any existing listeners handle_simple object name old new Handles a trait change for an intermediate link trait handle_dst object name old new Handles a trait change for an intermediate link trait when the notification is for the final destination trait handle list object name old new Handles a trait
213. t which is empty if all the attributes were successfully reset Description Resets each of the traits whose names are specified in the traits list to their default values If traits is None or omitted the method resets all explicitly defined object trait attributes to their default values Note that this does not affect wildcard trait attributes or trait attributes added via add_trait unless they are explicitly named in traits copyable trait names metadata Returns the list of trait names to copy or clone by default all trait names Returns the list of all trait names including implicitly defined traits copy traits other traits None memo None copy None metadata Copies another object s trait attributes into this one Parameters e other object The object whose trait attribute values should be copied e traits list of strings A list of names of trait attributes to copy If None or unspecified the set of names returned by trait_names is used If all or an empty list the set of names returned by all_trait_names is used 66 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 e memo dict A dictionary of objects that have already been copied e copy None deep shallow The type of copy to perform on any trait that does not have explicit copy metadata A value of None means copy reference Returns unassignable li
214. t has changed during the execution of the code inside the with statement similar to the assertRaises method Please note that in that case the context manager returns itself and the user can introspect the information of The last event fired by accessing the event attribute of the returned object eAll the fired events by accessing the events attribute of the return object Note that in the case of chained properties trait foo depends on bar which in turn depends on baz the order in which the corresponding trait events appear in the events attribute is not well defined and may depend on dictionary ordering Example class MyClass HasTraits number Float 2 0 my class MyClass with self assertTraitChangesExactly my_class number count 1 my_class number 3 0 Parameters e obj HasTraits The HasTraits class instance whose class trait will change e trait str The extended trait name of trait changes to listen to e count int or None optional The expected number of times the event should be fired When None default value there is no check for the number of times the change event was fired e callableObj callable optional A callable object that will trigger the expected trait change When None default value a trigger is expected to be called under the context manger returned by this method e xargs List of positional arguments for cal lableOb 4 e xxkwar
215. t two arguments project and resource_path are the same as for the function find_resource in this module The third argument filename is the name of the file which will be created or overwritten if it already exists The return value in always None 126 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 import_symbol Module A function to import symbols traits util import_symbol import_symbol symbol_path Import the symbol defined by the specified symbol path Examples import_symbol tarfile TarFile gt TarFile import_symbol tarfile TarFile open gt TarFile open To allow compatibility with old school traits symbol names we also allow all dotted paths but in this case you can only import top level names from the module import_symbol tarfile TarFile gt TarFile toposort Module A simple topological sort on a dictionary graph exception traits util toposort CyclicGraph Bases exceptions Exception Exception for cyclic graphs traits util toposort topological_sort graph Returns the nodes in the graph in topological order trait _documenter Module A Trait Documenter Subclassed from the autodoc ClassLevelDocumenter copyright Copyright 2012 by Enthought Inc class traits util trait_documenter TraitDocumenter directive name indent u Bases sphinx ext autodoc ClassLevelDocumenter Specialized Documenter subclass for trait attributes The c
216. t_get names metadata Shortcut for getting object trait attributes Parameters names list of strings A list of trait attribute names whose values are requested Returns result dict A dictionary whose keys are the names passed as arguments and whose values are the corresponding trait values Description Looks up the value of each trait whose name is passed as an argument and returns a dictionary containing the resulting name value pairs If any name does not correspond to a defined trait it is not included in the result If no names are specified the result is a dictionary containing name value pairs for all traits defined on the object get args kw Shortcut for getting object trait attributes Parameters names list of strings A list of trait attribute names whose values are requested 64 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 Returns result dict A dictionary whose keys are the names passed as arguments and whose values are the corresponding trait values Description Looks up the value of each trait whose name is passed as an argument and returns a dictionary containing the resulting name value pairs If any name does not correspond to a defined trait it is not included in the result If no names are specified the result is a dictionary containing name value pairs for all traits defined on the object trait set trait_change_notify True trait
217. t_value Eraits 57 traits_list ustr_trait 1 124 til traits traits traits traits traits traits til deprec til til til ga El import resour g g gam gig T H test_tools 121 e_tools 121 ttest_tools 121 trait_base 82 s 84 ers 84 iers 115 ic 93 94 110 ener 111 116 async trait wait 124 til camel case 124 clean strings 125 ated 125 event tracer 128 home_directory 125 _symbol 127 ce 126 131 Traits 4 User Manual Release 4 6 0 dev354 132 Python Module Index Index Symbols _InstanceArgs class in traits traits 61 _TraitMaker class in traits traits 61 __call__ traits has_traits MetaInterface method 62 __getstate__ 47 overriding 48 init 0 traits adapter Adapter method 61 __init_ traits has traits MetaHasTraitsObject method 63 __init__ traits has_traits MetaInterface method 62 __init__ traits trait_types BaseTuple method 105 __init__ traits trait_types ValidatedTuple method 105 __setstate__ 47 overriding 48 _any_trait_changed examples 18 _anytrait_changed 20 _arg_count in module traits trait_handlers 93 _name_changed 18 19 _name_default 32 name fired0 18 read only in module traits trait_handlers 93 _undefined_get in module traits trait_handlers 93 _undefined_set in module traits trait_handlers 93 _write_only in m
218. tance List or Dict In the case of List and Dict traits the subsequent portion of the pattern is applied to each item in the list or value in the dictionary For example if the self children is a list children name listens for trait changes to the name trait for each item in the self children list Note that items added to or removed from a list or dictionary in the pattern will cause the handler routine to be invoked as well since this is treated as an implied change to the item s trait being monitored The signature of the handler supplied also has an effect on how changes to intermediate traits are pro cessed The five valid handler signatures are 74 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 1 handler 2 handler new 3 handler name new 4 handler object name new 5 handler object name old new For signatures 1 4 and 5 any change to any element of a path being listened to invokes the handler with in formation about the particular element that was modified e g if the item being monitored is foo bar baz a change to bar will call handler with the following information eobject object foo ename bar eold old value for object foo bar enew new value for object foo bar If one of the intermediate links is a List or Dict the call to handler may report an _items changed event If in the previous example bar is a List and a new item is added to bar then t
219. tandard metadata for the trait class traits trait_types HTML value minlen 0 maxlen 9223372036854775807 regex metadata Defines a trait whose value must be a string that is interpreted as being HTML By default the value is parsed and displayed as HTML in TraitsUI views The validation of the value does not enforce HTML syntax metadata editor function html_editor at 0x7f44979957d0 gt The standard metadata for the trait class traits trait_types Password value minlen 0 maxlen 9223372036854775807 regex metadata Defines a trait whose value must be a string optionally of constrained length or matching a regular expression The trait is identical to a String trait except that by default it uses a PasswordEditor in TraitsUI views which obscures text entered by the user metadata editor function password_editor at 0x7f4497c0fcf8 gt The standard metadata for the trait class traits trait_types Callable default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be a Python callable metadata copy ref The standard metadata for the trait default_value None The default value for the trait info_text a callable value A description of the type of value this trait accepts validate object name value Validates that the value is a Python callable class traits trait_types BaseType
220. tation manager to a new AdaptationManager instance traits adaptation adaptation_manager get_global_adaptation_manager Set a reference to the global adaptation manager traits adaptation adaptation_manager adapt adaptee to_protocol default lt class traits adaptation adaptation_error AdaptationError gt Attempt to adapt an object to a given protocol traits adaptation adaptation_manager register_factory factory from_protocol to_protocol Register an adapter factory traits adaptation adaptation_manager register_offer offer Register an offer to adapt from one protocol to another traits adaptation adaptation_manager register_provides provider_protocol proto col Register that a protocol provides another traits adaptation adaptation_manager supports_protocol obj protocol Does the object support a given protocol traits adaptation adaptation_manager provides_protocol type_ protocol Does the given type provide i e implement a given protocol adaptation_offer Module An offer to provide adapters from one protocol to another class traits adaptation adaptation_offer AdaptationOffer Bases traits has_traits HasTraits An offer to provide adapters from one protocol to another An adaptation offer consists of a factory that can create adapters and the protocols that define what the adapters adapt from and to factory Property Any A factory for creating adapters The factory must ba callabl
221. tching value This shorthand is useful when a number of trait attributes need to be set on an object or a trait attribute value needs to be set in a lambda function For example person trait_set name Bill age 27 The statement above is equivalent to the following person name Bill person age 27 add_class_trait The add_class_trait method is a class method while the preceding HasTraits methods are instance methods This method is very similar to the add_trait instance method The difference is that adding a trait attribute by using add_class_trait is the same as having declared the trait as part of the class definition That is any trait attribute added using add_class_trait is defined in every subsequently created instance of the class and in any subsequently defined subclasses of the class In contrast the add_trait method adds the specified trait attribute only to the object instance it is applied to In addition if the name of the trait attribute ends with a _ then a new or replacement prefix rule is added to the class definition just as if the prefix rule had been specified statically in the class definition It is not possible to define new prefix rules using the add_trait method 1 1 Traits 4 User Manual 49 Traits 4 User Manual Release 4 6 0 dev354 One of the main uses of the add_class_trait method is to add trait attribute definitions that could not be defined stati
222. te 113 deferred traits traits_listener Listenerltem attribute 112 defining trait with 9 delegate metadata attribute 10 Delegate class in traits trait_types 102 delegate traits trait_value Trait Value attribute 111 delegate parameter to DelegatesTo initializer 21 DelegatesTo built in class 21 DelegatesTo class in traits trait_types 103 delegation 21 examples 21 DelegationError class in traits trait_errors 84 depends_on metadata 46 deprecated in module traits testing nose_tools 121 deprecated in module traits util deprecated 125 desc metadata attribute 11 Dict class in traits trait_types 107 Dict 7 dictionary parameter to Trait 27 DictStrAny in module traits trait_types 110 DictStrBool in module traits trait_types 110 DictStrFloat in module traits trait_types 110 DictStrInt in module traits trait_types 110 DictStrList in module traits trait_types 110 DictStrLong in module traits trait_types 110 DictStrStr in module traits trait_types 110 directivetype traits util trait_documenter TraitDocumenter attribute 127 Directory class in traits trait_types 104 Directory 7 Disallow 7 object 35 Disallow in module traits trait_types 102 dispatch traits traits_listener ListenerGroup attribute 113 dispatch traits traits_listener ListenerItem attribute 112 dispatch traits trait_notifiers TraitChangeNotify Wrapper method 115 doctest_for_module in traits testin
223. te__ method uses a more generic approach which developers can customize through the use of traits metadata attributes often without needing to override or define a __getstate__ method in their application classes In particular the HasTraits __getstate__ method discards the values of all trait attributes that have the transient metadata attribute set to True and saves all other trait attributes So to mark which trait values should not be saved you set transient to True in the metadata for those trait attributes The benefits of this approach are that you do not need to override __getstate__ and that the metadata helps document the pickling behavior of the class For example transient_metadata py Example of using transient metadata from traits api import HasTraits File Any class DataBase HasTraits The name of the data base file file_name File The open file handle used to access the data base file Any transient True In this example the DataBase class s file trait is marked as transient because it normally contains an open file handle used to access a data base Since file handles typically cannot be pickled and restored the file handle should not be saved as part of the object s persistent state Normally the file handle would be re opened by application code after the object has been restored from its persisted state 1 1 Traits 4 User Manual 47 Traits 4 User Manual Releas
224. tem at tribute 112 metadata_name traits traits_listener Listenerltem tribute 112 MetaHasTraits class in traits has_traits 62 MetaHasTraitsObject class in traits has_traits 62 MetalInterface class in traits has_traits 62 Method class in traits trait_types 102 MethodQ 7 migrate_property traits has_traits MetaHasTraitsObject method 63 Missing in module traits trait_base 83 Module class in traits trait_types 102 Module 7 mro_distance_to_protocol at validate 26 new traits util event_tracer ChangeMessageRecord at tribute 128 new parameter to the notification handlers 16 NewTraitChangeNotify Wrapper class in traits trait_notifiers 115 next traits traits_listener ListenerGroup attribute 113 next traits traits_listener Listenerltem attribute 112 next traits traits_listener ListenerParser attribute 14 no_adapter_necessary in module traits adaptation adaptation_manager 17 NoDefaultSpecified in module traits trait handlers 86 not_event in module traits trait_base 83 not_event in module traits traits_listener 111 not_false in module traits trait_base 83 not_none in module traits trait_base 83 notification 2 dynamic 13 15 special cases 16 specially named handlers 18 static 17 strategies 12 NotificationExceptionHandler class in traits trait_notifiers 115 NotificationExceptionHandlerState class in traits trait_notifiers 115 notify traits tra
225. tem type when a list item is removed from the monitored list info_text a unique string The informational text describing the trait validate object name value Ensures that a value being assigned to a trait is a unique string class traits ustr_trait HasUniqueStrings Bases traits has_traits HasTraits Mixin or base class for objects containing lists with items containing string valued traits that must be unique List traits within the class that contain items which have string traits which must be unique should indicate this by attaching metadata of the form unique_string traiti trait2 traitn where each traiti value is the name of a trait within each list item that must contain unique string data For example usa List State unique_string name abbreviation traits init Adds any UStrMonitor objects to list traits with unigue string metadata 2 1 2 Subpackages adaptation Package adaptation Package Adaptation package Copyright 2013 Enthought Inc adaptation_error Module Exception raised when a requested adaptation is not possible exception traits adaptation adaptation_error AdaptationError Bases exceptions TypeError Exception raised when a requested adaptation is not possible 116 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 adaptation_manager Module Manages all registered adaptation
226. ters to the initializer function specify additional information about how to do the prototyping Keyword Parameters The prefix and listenable parameters of the DelegatesTo and PrototypedFrom initializer functions behave similarly for both classes Prefix Keyword When the prefix parameter is a non empty string the rule for performing trait attribute look up in the deferred to object is modified with the modification depending on the format of the prefix string 22 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 e If prefix is a valid Python attribute name then the original attribute name is replaced by prefix when looking up the deferred to attribute e If prefix ends with an asterisk and is longer than one character then prefix minus the trailing asterisk is added to the front of the original attribute name when looking up the object attribute e If prefix is equal to a single asterisk the value of the object class s __ prefix__ attribute is added to the front of the original attribute name when looking up the object attribute Each of these three possibilities is illustrated in the following example using PrototypedFrom prototype_prefix py Examples of PrototypedFrom prefix parameter from traits api import PrototypedFrom Float HasTraits Instance Str class Parent HasTraits first_name Str family_name favorite first name Str child_
227. that attribute s trait as the result validate trait name value Validates whether a value is legal for a trait 76 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 Returns the validated value if it is valid traits metadata Returns a dictionary containing the definitions of all of the trait attributes of this object that match the set of metadata criteria Parameters metadata Criteria for selecting trait attributes Description The keys of the returned dictionary are the trait attribute names and the values are their corresponding trait definition objects If no metadata information is specified then all explicitly defined trait attributes defined for the object are returned Otherwise the metadata keyword dictionary is assumed to define a set of search criteria for selecting trait attributes of interest The metadata dictionary keys correspond to the names of trait metadata attributes to examine and the values correspond to the values the metadata attribute must have in order to be included in the search results The metadata values either may be simple Python values like strings or integers or may be lambda expres sions or functions that return True if the trait attribute is to be included in the result A lambda expression or function must receive a single argument which is the value of the trait metadata attribute being tested If more than one metadata keyword is specified a
228. the cached value file contents which is maintained by the cached_property wrapper code is returned traits has_traits provides protocols Class decorator to declare the protocols that a class provides Parameters protocols A list of protocols Interface classes or Python ABCs that the deco rated class provides traits has_traits weak_arg arg Create a weak reference to arg and wrap the function so that the dereferenced weakref is passed as the first argument If arg has been deleted then the function is not called has_dynamic_views Module Provides a framework that assembles Traits UI Views at run time when the view is requested rather than at the time a class is written This capability is particularly useful when the object being viewed with a Traits UI is part of a plug in application such as Envisage In general this capability allows e The GUI for an object can be extendable by contributions other than from the original code writer e The view can be dynamic in that the elements it is composed of can change each time it is requested e Registration of a handler can be associated with the view contributions Either the original object writer or a contributor can use this framework to declare one or more dynamic views that are composed of sub elements that only need to exist at the time the view is requested 80 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 Users of t
229. the example joe Parent joe last name Johnson moe Child moe father joe DELEGATION in action print Moe s last name is s moe last name Result Moe s last name is Johnson NOTIFICATION in action moe age 10 Result Age changed from 0 to 10 VISUALIZATION Displays a UI for editing moe s attributes if a supported GUI toolkit is installed moe configure_traits Background Python does not require the data type of variables to be declared As any experienced Python programmer knows this flexibility has both good and bad points The Traits package was developed to address some of the problems caused by not having declared variable types in those cases where problems might arise In particular the motivation for Traits came as a direct result of work done on Chaco an open source scientific plotting package Chaco provides a set of high level plotting objects each of which has a number of user settable attributes such as line color text font relative location and so on To make the objects easy for scientists and engineers to use the attributes attempt to accept a wide variety and style of values For example a color related attribute of a Chaco object might accept any of the following as legal values for the color red e red e OxFFOO00 e 1 0 0 0 0 0 1 0 Thus the user might write plotitem color red In a predecessor to Chaco providing such flexibility
230. the trait attribute are limited to either yes or no That is if the value y is assigned to the married attribute the actual value assigned will be yes Note that the algorithm used by TraitPrefixList in determining whether a string is a valid value is fairly efficient in terms of both time and space and is not based on a brute force set of comparisons traits trait_handlers TraitMap map Checks that the value assigned to a trait attribute is a key of a specified dictionary and also assigns the dictionary value corresponding to that key to a shadow attribute A trait attribute that uses a TraitMap handler is called mapped trait attribute In practice this means that the resulting object actually contains two attributes one whose value is a key of the TraitMap dictionary and the other whose value is the corresponding value of the TraitMap dictionary The name of the shadow attribute is simply the base attribute name with an underscore _ appended Mapped trait attributes can be used to allow a variety of user friendly input values to be mapped to a set of internal program friendly values Example gt gt gt class Person HasTraits 2 married Trait yes TraitMap yes 1 no 0 gt gt gt gt gt gt bob Person gt gt gt print bob married yes gt gt gt print bob married_ 1 class In this example the default value of the married attribute of the Person class is yes B
231. to the trait attribute Any trait that uses a TraitCastType instance in its definition ensures that its value is of the type associated with the TraitCastType instance For example class Person HasTraits name Trait TraitCastType weight Trait 0 0 TraitCastType float 2 1 API Reference 89 Traits 4 User Manual Release 4 6 0 dev354 In this example the name trait must be of type str string while the weight trait must be of type float Note that this example is essentially the same as writing class Person HasTraits name CStr weight CFloat To understand the difference between TraitCoerceType and TraitCastType and also between Float and CFloat consider the following example gt gt gt class Person HasTraits weight Float 8 cweight CFloat gt gt gt gt gt gt bill Person gt gt gt bill weight 180 OK coerced to 180 0 gt gt gt bill cweight 180 OK cast to 180 0 gt gt gt bill weight 180 Error invalid coercion gt gt gt bill cweight 180 OK cast to float 180 class traits trait_handlers ThisClass allow_none False Ensures that the trait attribute values belong to the same class or a subclass as the object containing the trait attribute ThisClass is the underlying handler for the predefined traits This and self and the elements of ListThis class traits trait_handlers TraitInstance aClass allow_no
232. traits adapter module 61 traits api importing from 4 traits category module 61 traits etsconfig module 120 traits etsconfig etsconfig module 120 traits has_dynamic_views module 80 traits has_traits module 62 traits interface_checker module 82 traits protocols module 120 traits testing module 120 traits testing doctest_tools module 121 traits testing nose_tools module 121 traits testing unittest_tools module 121 traits trait_base module 82 traits trait_errors module 84 traits trait_handlers module 84 traits trait_notifiers module 115 traits trait_numeric module 93 traits trait_types module 94 traits trait_value module 110 traits traits module 57 traits traits_listener module 111 traits ustr_trait module 116 traits util module 124 traits util async_trait_wait module 124 traits util camel_case module 124 traits util clean_strings module 125 traits util deprecated module 125 traits util event_tracer module 128 traits util home_directory module 125 traits util import_symbol module 127 traits util resource module 126 traits util toposort module 127 traits util trait_documenter module 127 traits_home in module traits trait_base 83 traits init traits ustr_trait HasUniqueStrings method 116 traits_super class in traits has_traits 78 TraitSetEvent class in traits trait_handlers 93 TraitSetObject class in traits trait_handlers 9
233. traits trait_types 109 method 129 save_to_fileQ traits util event_tracer RecordContainer method 129 self class in traits trait_types 101 Self in module traits trait_base 83 self trait 8 semantics extended trait names 14 on_trait_change 18 SentinelRecord class in traits util event_tracer 128 Set class in traits trait_types 106 set 26 49 set traits has_traits HasTraits method 65 SetQ StringQ 7 set_global_adaptation_manager in module traits adaptation adaptation_manager 118 set_trait_dispatch_handler traits has_traits HasTraits class method 64 set_ui_handler in module traits trait_notifiers 115 set_value traits trait_handlers TraitType method 87 setup in module traits util trait_documenter 128 shadow values 28 shell_editor in module traits traits 60 simple types 5 SingletonHasPrivateTraits class in traits has_traits 78 SingletonHasStrictTraits class in traits has_traits 78 SingletonHasTraits class in traits has_traits 78 skip in module traits testing nose_tools 121 skip_ws traits traits_listener ListenerParser attribute 114 source traits util event_tracer CallingMessageRecord at tribute 128 static notification examples 18 StaticAnyTraitChangeNotifyWrapper class in traits trait_notifiers 115 StaticTraitChangeNotify Wrapper class in traits trait_notifiers 115 store_resource in module traits util resource 126 Str class in traits trait
234. tribute Description The string should be a phrase describing the type defined by the TraitHandler subclass rather than a complete sentence For example use the phrase a square sprocket instead of the sentence The value must be a square sprocket The value returned by full_info is combined with other information whenever an error occurs and therefore makes more sense to the user if the result is a phrase The full info method is similar in purpose and use to the info attribute of a validator function Note that the result can include information specific to the particular trait handler instance For example TraitRange instances return a string indicating the range of values acceptable to the handler e g an integer in the range from to 9 If the full_info method is not overridden the default method returns the value of calling the info method info Must return a string describing the type of value accepted by the trait handler The string should be a phrase describing the type defined by the TraitHandler subclass rather than a complete sentence For example use the phrase a square sprocket instead of the sentence The value must be a square sprocket The value returned by info is combined with other information whenever an error occurs and therefore makes more sense to the user if the result is a phrase The info method is similar in purpose and use to the info attribute of a validator funct
235. tribute Name Wildcard The Traits package enables you to define a category of trait attributes associated with a particular trait definition by including an underscore as a wildcard at the end of a trait attribute name For example temp_wildcard py Example of using a wildcard with a Trait attribute name from traits api import Any HasTraits class Person HasTraits temp_ Any 1 1 Traits 4 User Manual 33 Traits 4 User Manual Release 4 6 0 dev354 This example defines a class Person with a category of attributes that have names beginning with temp and that are defined by the Any trait Thus any part of the program that uses a Person instance can reference attributes such as tempCount temp_name or temp_whatever without having to explicitly declare these trait attributes Each such attribute has None as the initial value and allows assignment of any value because it is based on the Any trait You can even give all object attributes a default trait definition by specifying only the wildcard character for the attribute name all_wildcard py Example of trait attribute wildcard rules from traits api import Any HasTraits Int Str class Person HasTraits Normal explicitly defined trait name Str By default let all traits have any value Any Except for this one which must be an Int age Int gt gt gt bill Person gt gt gt These ass
236. ts and so will return an empty tuple The exceptions are List and Dict trait types which have inner traits used to validate the values assigned to the trait For example in List Int the inner traits for List are Int traits trait_handlers NoDefaultSpecified class traits trait_handlers TraitType default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Base class for new trait types This class enables you to define new traits using a class based approach instead of by calling the Trait factory function with an instance of a TraitHandler derived object When subclassing this class you can implement one or more of the method signatures below Note that these methods are defined only as comments because the absence of method definitions in the subclass definition implicitly provides information about how the trait should operate The optional methods are as follows eget self object name This is the getter method of a trait that behaves like a property Parameters object object The object that the property applies to name str The name of the property on object property Description If neither this method nor the set method is defined the value of the trait is handled like a normal object attribute If this method is not defined but the set method is defined the trait behaves like a write only property This method should return the value of the name property for the object obj
237. ts trait_types CSet trait None value None items True metadata Defines a trait whose values must be a set whose items are of the specified trait type or which can be coerced to a set whose values are of the specified trait type validate object name value Validates that the values is a valid list full_info object name value Returns a description of the trait class traits trait_types Dict key_trait None value_trait None value None items True etadata Defines a trait whose value must be a dictionary optionally with specified types for keys and values validate object name value Validates that the value is a valid dictionary Note object can be None when validating a default value see e g clone full_info object name value Returns a description of the trait create editor Returns the default UI editor for the trait inner _traits Returns the inner trait or traits for this trait class traits trait_types BaseClass default_value lt traits trait_handlers NoDefaultSpecified ob ject gt metadata Base class for types which have an associated class which can be determined dynamically by specifying a string name for the class e g packagel package2 module class Any subclass must define instances with klass and module attributes that contain the string name of the class or actual class object and the module name that contained the original trait definition u
238. ttribute changes The class specific notification handler is _anytrait_changed and is called when weight_kg height_m or bmi changes Thus both handlers are called when the weight_kg attribute changes Also the weight kg changed function modifies the bmi attribute which causes _anytrait_changed to be called for that attribute The arguments that are passed to the trait attribute change notification method depend on the method signature and on which type of static notification handler it is Attribute specific Handler Signatures For an attribute specific notification handler the method signatures supported are _name_changed _name_changed new _name_changed old new _name_changed name old new The method name can also be _name_fired with the same set of signatures In these signatures e new is the new value assigned to the trait attribute For List and Dict objects this is a list of the items that were added e old is the old value assigned to the trait attribute For List and Dict objects this is a list of the items that were deleted e name is the name of the trait attribute The extended trait name syntax is not supported Note that these signatures follow a different pattern for argument interpretation from dynamic handlers and decorated static handlers Both of the following methods define a handler for an object s name trait def _name_changed self argl arg2 arg3 pass on_trait_chang
239. type alias of long default_value 0L The default value for the trait info text a long A description of the type of value this trait accepts validate object name value Validates that a specified value is valid for this trait Note The fast validator version performs this check in C create editor Returns the default traits UI editor for this type of trait class traits trait_types Long default_value lt traits trait_handlers NoDefaultSpecified objects metadata Defines a trait whose value must be a Python long using a C level fast validator fast_validate 11 type long gt None type int gt The C level fast validator to use class traits trait_types BaseFloat default_value lt traits trait_handlers NoDefaultSpecified ob ject gt metadata Defines a trait whose value must be a Python float 2 1 API Reference 95 Traits 4 User Manual Release 4 6 0 dev354 evaluate The function to use for evaluating strings to this type alias of float default_value 0 0 The default value for the trait info text a float A description of the type of value this trait accepts validate object name value Validates that a specified value is valid for this trait Note The fast validator version performs this check in C create editor Returns the default traits UI editor for this type of trait class traits trait_types Float default_val
240. ue lt traits trait_handlers NoDefaultSpecified objects metadata Defines a trait whose value must be a Python float using a C level fast validator fast_validate 11 lt type float gt None lt type int gt lt type long gt The C level fast validator to use class traits trait_types BaseComplex default_value lt traits trait_handlers NoDefaultSpecified object gt metadata Defines a trait whose value must be a Python complex evaluate The function to use for evaluating strings to this type alias of complex default_value 0j The default value for the trait info text a complex number A description of the type of value this trait accepts validate object name value Validates that a specified value is valid for this trait Note The fast validator version performs this check in C create editor Returns the default traits UI editor for this type of trait class traits trait_types Complex default_value lt traits trait_handlers NoDefaultSpecified ob ject gt metadata Defines a trait whose value must be a Python complex using a C level fast validator fast_validate 11 type complex gt None type float gt type int gt The C level fast validator to use class traits trait_types BaseStr default_value lt traits trait_handlers NoDefaultSpecified ob ject gt metadata Defines a trait whose value must be a Python string
241. uld not be reported iteml A list which matches any of the specified items Note that at the topmost level item2 the surrounding square brackets are optional itemN name If the current object does not have an attribute called name the reference can be ignored If the character is omitted the current object must have a trait called name otherwise an exception will be raised prefixt Matches any trait on the object whose name begins with prefix metadata_name Matches any trait on the object having metadata_name metadata metadata name Matches any trait on the object which does not have metadata_name metadata prefix metadat a Maiahes any trait on the object whose name begins with prefix and which has metadata_name metadata prefix metadat a Mnatates any trait on the object whose name begins with prefix and which does not have metadata_name metadata Matches all traits on the object pattern Matches object graphs where pattern occurs one or more times useful for setting up listeners on recursive data structures like trees or linked lists Some examples of valid names and their meaning are as follows example meaning foo bar baz Listen for trait changes to object foo object bar and object baz foo bar Equbvatent to foo bar baz but may be more useful in cases where the individual items are computed foo bar bag4 Listen for trait change
242. urn NDArrayTolImage adaptee adaptee return None somewhere else at application startup register_factory ndarray_to_image_abc numpy ndarray ImageABC 1 1 Traits 4 User Manual 41 Traits 4 User Manual Release 4 6 0 dev354 Try to adapt numpy arrays to images The adapt function is introduced later in the docs but you can probably guess what it does This adaptation fails as the array is 1D image adapt numpy ndarray 1 2 3 ImageABC default None assert image None This succeeds image adapt numpy array 1 2 3 4 ImageABC assert isinstance image NDArrayTolImage Requesting an adapter The adapt function Adapter classes are defined as described in the preceding sections but you do not explicitly create instances of these classes Instead the function adapt is used giving the object that needs to be adapted and the target protocol For instance in the example in the Conditional adaptation section a 2D numpy array is adapted to an ImageABC protocol with image adapt numpy array 1 2 3 4 ImageABC In some cases no single adapter class is registered that adapts the object to the required interface but a series of adapter classes exist that together perform the required adaptation In such cases the necessary set of adapter objects are created and the last link in the chain the one that actually implements the required inte
243. v354 expression meaning iteml item2 means item is a trait containing an object or objects if item is a list or dict with a trait called item2 Changes to either item or item2 cause a notification to be generated iteml item2 means item is a trait containing an object or objects if ifem is a list or dict with a trait called item2 Changes to item2 cause a notification to be generated while changes to item do not i e the indicates that changes to the link object should not be reported iteml A list which matches any of the specified items Note that at the topmost level item2 the surrounding square brackets are optional itemN name If the current object does not have an attribute called name the reference can be ignored If the character is omitted the current object must have a trait called name otherwise an exception will be raised prefixt Matches any trait on the object whose name begins with prefix metadata_name Matches any trait on the object having metadata_name metadata metadata_name Matches any trait on the object which does not have metadata_name metadata prefix metadat a Maiahes any trait on the object whose name begins with prefix and which has metadata_name metadata prefix metadat a Mnatates any trait on the object whose name begins with prefix and which does not have metadata_name metadata Matches all traits on th
244. validator method 104 init_fast_validator method 104 init_fast_validator method 105 init_fast_validator traits trait_types Enum method 104 init_fast_validator traits trait_types Range method 104 init_fast_validator traits trait_types Tuple method 105 initialization 2 dynamic 32 inner_traits metadata attribute 10 inner_traits traits trait_handlers BaseTraitHandler method 86 inner_traits traits trait_types Dict method 107 inner_traits traits trait_types List method 106 inner_traits traits trait_types Set method 107 Instance class in traits trait_types 108 Instance 7 Int class in traits trait_types 95 Int trait 5 int_validate traits trait_types BaseRange method 104 integer type long 5 plain 5 Interface class in traits has_traits 78 InterfaceChecker class in traits interface_checker 82 InterfaceError class in traits interface_checker 82 interfaces 36 defining 37 implementation example 37 implementing 37 using 38 is_any_trait traits traits_listener ListenerItem attribute 112 traits trait_types BaseInstance traits trait_types BaseEnum traits trait_types BaseRange traits trait_types BaseTuple K keywords traits has_dynamic_views DynamicView at tribute 82 keywords traits has_dynamic_views DynamicViewSubElement attribute 81 klass traits has_dynamic_views Dynamic ViewSubElement attribute 81 kw traits trait_value Trait Value attri
245. value BaseTraitValue as ctrait original trait Returns the low level C based trait for this Trait Value class traits trait_value TraitValue default Callable The callable used to define a default value args Tuple The positional arguments to pass to the callable default value kw Dict The keyword arguments to pass to the callable default value type Any The trait to use as the new trait type delegate Instance HasTraits The object to delegate the new value to name Str The name of the trait on the delegate object to get the new value from Functions traits trait_value SyncValue delegate name traits trait_value TypeValue type traits trait_value DefaultValue default args kw traits listener Module Defines classes used to implement and manage various trait listener patterns traits traits_listener indent text first_line True n 1 width 4 Indent lines of text Parameters e text str The text to indent e first line bool optional If False then the first line will not be indented default True e n int optional The level of indentation default 1 e width int optional The number of spaces in each level of indentation default 4 Returns indented str traits traits_listener is_not_none value traits traits_ listener is_none value traits traits_listener not_event value 2 1 API Reference 111 Traits 4 User
246. w_elements class method 68 class_traits traits has_traits HasTraits class method 77 class visible traits traits has_traits HasTraits class method 70 clean_filename in module traits util clean_strings 125 clean_timestamp in module traits util clean_strings 125 CList class in traits trait_types 106 clone traits trait_handlers TraitType method 87 clone_traits 49 clone_traits traits has_traits HasTraits method 67 CLong class in traits trait_types 98 CLong trait 5 traits has_traits HasTraits traits has_traits HasTraits create_editor traits trait_types BaseRange method 104 create_editor traits trait_types BaseStr method 97 create_editor traits trait_types BaseTuple method 105 create_editor traits trait_types BaseUnicode method 97 create_editor traits trait_types Dict method 107 create_editor traits trait_types List method 106 create_editor traits trait_types Set method 106 create_editor traits trait_types String method 100 create_editor traits trait_types Title method 97 create_unique_name in module traits util resource 126 CSet class in traits trait_types 107 CSet 7 CStr class in traits trait_types 99 close traits util event_tracer MultiThreadChangeEventRecOMetrait 5 method 129 Code class in traits trait_types 100 Code 7 code_editor in module traits traits 60 coercing types 5 6 Colo
247. which can take one of three values e 0 default Does not check whether classes implement their declared interfaces e 1 Verifies that classes implement the interfaces they say they do and logs a warning if they don t e 2 Verifies that classes implement the interfaces they say they do and raises an InterfaceError if they don t The CHECK_INTERFACES variable must be imported directly from the traits has_traits module import traits has_traits traits has_traits CHECK_INTERFACES 1 Using Interfaces You can use an interface at any place where you would normally use a class name The most common way to use interfaces is with the Instance or Supports traits gt gt gt from traits api import HasTraits Instance gt gt gt class Apartment HasTraits renter Instance IName gt gt gt william Person first_name William last_name Adams gt gt gt aptl Apartment renter william gt gt gt print Renter is aptl renter get_name Renter is William Adams Using an interface class with an Instance trait definition declares that the trait accepts only values that implement the specified interface Using the Supports traits if the assigned object does not implement the interface the Traits package may automatically substitute an adapter object that implements the specified interface See Adaptation for more information Adaptation The adaptation features of Traits have bee
248. will always work no matter which other packages are present protocols Package Note The traits protocols package is deprecated Use the traits adaptation package instead in new code Trivial Interfaces and Adaptation from PyProtocols This package used to be a subset of the files from Phillip J Eby s PyProtocols package The package has been substituted by traits adaptationas of Traits 4 4 0 Currently the package contains deprecated aliases for backward compatibility and will be removed in Traits 5 0 testing Package testing Package Scripts and assert tools related to running unit tests These scripts also allow running test suites in separate processes and aggregating the results 120 Chapter 2 Developer Reference Traits 4 User Manual Release 4 6 0 dev354 doctest_tools Module Tools for having doctest and unittest work together more nicely Eclipse s PyDev plugin will run your unittest files for you very nicely The doctest_for_module function allows you to easily run the doctest for a module along side your standard unit tests within Eclipse traits testing doctest_tools doctest_for_module module Create a TestCase from a module s doctests that will be run by the standard unittest main Example tests test_foo py import unittest import foo from traits testing api import doctest_for_module class FooTestCase unittest TestCase class FooDocTest doctest_for_module foo p
249. ws DynamicView Declares a dynamic view id Str The ID of the view This is the ID that the view s preferences will be saved under 2 1 API Reference 81 Traits 4 User Manual Release 4 6 0 dev354 name Str The name of the view This is the name that should be requested when calling edit_traits or config ure_traits keywords Dict Keyword arguments passed in during construction of the actual view instance use as default Bool False Indicates whether this view should be the default traits view for objects it is contributed to class traits has_dynamic_views HasDynamicViews Provides of a framework that builds Traits UI Views at run time when the view is requested rather than at the time a class is written trait view name None view_element None Gets or sets a ViewElement associated with an object s class Extended here to build dynamic views and sub elements declare_dynamic_view declaration A convenience method to add a new dynamic view declaration to this instance interface_checker Module An attempt at type safe casting Classes class traits interface_checker InterfaceError The exception raised if a class does not really implement an interface class traits interface_checker InterfaceChecker Checks that interfaces are actually implemented check_implements cls interfaces error_mode Checks that the class implements the specified interfaces interfaces can be a single inter
250. y to define either a trait type or a trait property depending on the specific methods and class constants that you define A trait type uses a validate method while a trait property uses get and set methods Defining a Trait Type The members that are specific to a trait type subclass are e validate method e post_setattr method e default_value attribute or get_default_value method Of these only the validate method must be overridden in trait type subclasses A trait type uses a validate method to determine the validity of values assigned to the trait Optionally it can define a post_setattr method which performs additional processing after a value has been validated and assigned All of the basic predefined traits such as Float and Str have a BaseType version that does not have the fast_validate attribute 1 1 Traits 4 User Manual 25 Traits 4 User Manual Release 4 6 0 dev354 The signatures of these methods are validate object name value post_setattr object name value The parameters of these methods are e object The object whose trait attribute whose value is being assigned e name The name of the trait attribute whose value is being assigned e value The value being assigned The validate method returns either the original value or any suitably coerced or adapted value that is legal for the trait If the value is not legal and cannot be coerced or adapted to be legal the method
251. yProject data image jpg resource_path would be data image jpg e alt path str The path to the resource relative to the location of the application s top level script the one with main If this function is called in code scripts myscript py and the resource is code data image jpg the alt path would be data image jpg This path is only used if the resource cannot be found using setuptools e return path bool Determines whether the function should return a file object or a full path to the resource Returns file file object or file path A file object containing the resource If return path is True file will be the full path to the resource If the file is not found or cannot be opened None is returned Description This function will find a desired resource file and return an opened file object The main method of finding the resource uses the pkg_resources resource_stream method which searches your working set for the installed project specified and appends the resource_path given to the project path leading it to the file If setuptools is not installed or it cannot find open the resource find_resource will use the sys path 0 to find the resource if alt_path is defined traits util resource store_resource project resource_path filename Store the content of a resource given by the name of the project and the path relative to the root of the project into a newly created file The firs
252. ype Returns the type of the trait which is typically a handler derived from TraitType 10 Chapter 1 User Reference Traits 4 User Manual Release 4 6 0 dev354 type One of the following depending on the nature of the trait constant delegate event property trait Recognized Metadata Attributes The following metadata attributes are not predefined but are recognized by HasTraits objects desc A string describing the intended meaning of the trait It is used in exception messages and fly over help in user interface trait editors editor Specifies an instance of a subclass of TraitEditor to use when creating a user interface editor for the trait Refer to the TraitsUI User Manual for more information on trait editors label A string providing a human readable name for the trait It is used to label trait attribute values in user interface trait editors rich_compare A Boolean indicating whether the basis for considering a trait attribute value to have changed is a rich comparison True the default or simple object identity False This attribute can be useful in cases where a detailed comparison of two objects is very expensive or where you do not care if the details of an object change as long as the same object is used trait_value A Boolean indicating whether the trait attribute accepts values that are instances of TraitValue The default is False The TraitValue class provides a mechani
253. ypes TraitDict also makes sure that any changes to keys or values made that are made after the dictionary is assigned to the trait attribute satisfy the type constraints TraitDict is the underlying handler for the dictionary based predefined traits and the Dict trait factory Example class WorkoutClass HasTraits member_weights Trait TraitDict str float This example defines a WorkoutClass class containing a member_weights trait attribute whose value must be a dictionary containing keys that are strings i e the members names and whose associated values must be floats i e their most recently recorded weight class traits trait_handlers TraitDictObject trait object name value Private Functions traits traits traits traits traits trait_handl trait_handl trait_handl trait_handl trait_handl lers _arg_count func Returns the correct argument count for a specified function or method lers _write_only object name ers read on1y object name value ers _undefined_get object name ers _undefined_set object name value trait numeric Module Trait definitions related to the numpy library 2 1 API Reference 93 Traits 4 User Manual Release 4 6 0 dev354 Classes class traits trait_numeric AbstractArray dtype None shape None value None class class class erce False typecode None metadata Abstract base class f

Download Pdf Manuals

image

Related Search

Related Contents

AIR-FLOW MASTER PIEZON®  EPM User Guide Spanish  MANUEL D`INSTALLATION ET DE MAINTENANCE - firma-web  Istruzioni per l`uso Apparecchio d`annuncio automatico  Xerox CopyCentre C128 Copier  ハンドメイド シェルリード線 取扱説明書 取り付けに便利な工具の紹介  Kraun KR.2J loudspeaker  LA PLANCHA DE A À Z - Inspirations Desjardins  CBR 1000 Manual 2008  Sea Gull Lighting 77270-839 Installation Guide  

Copyright © All rights reserved.
Failed to retrieve file