has_traits Module

Defines the HasTraits class, along with several useful subclasses and associated metaclasses.

Classes

class traits.has_traits.ViewElement[source]
class traits.has_traits.MetaHasTraits[source]
classmethod add_listener(listener, class_name='')[source]

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='')[source]

Removes a class creation listener.

class traits.has_traits.MetaInterface[source]

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__(*args, **kw)[source]

Attempt to adapt the adaptee to this interface.

Note that this means that (intentionally ;^) that interfaces cannot be instantiated!

class traits.has_traits.MetaHasTraitsObject(cls, class_name, bases, class_dict, is_category)[source]

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)[source]

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)[source]

Adds the Traits metadata to the class dictionary.

migrate_property(name, property, property_info, class_dict)[source]

Migrates an existing property to the class being defined (allowing for method overrides).

class traits.has_traits.HasTraits[source]

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 definition. They do not operate on trait attributes defined by way of wildcards or by calling add_trait(). For example:

>>>class Person(HasTraits):
...    name = Str
...    age  = Int
...    temp_ = Any
>>>bob = Person()
>>>bob.temp_lunch = 'sandwich'
>>>bob.add_trait('favorite_sport', Str('football'))
>>>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’: TraitChangeNotifyWrapper,
‘extended’: ExtendedTraitChangeNotifyWrapper,
‘new’: NewTraitChangeNotifyWrapper,
‘fast_ui’: FastUITraitChangeNotifyWrapper,
‘ui’: FastUITraitChangeNotifyWrapper}

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)[source]

Adds or removes the specified handler from the list of active monitors.

Parameters:
  • handler (function) – The function to add or remove as a monitor.
  • remove (bool) – Flag indicating whether to remove (True) or add the specified handler as a monitor for this class.

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)[source]

Adds a named trait attribute to this class.

Parameters:
  • name (str) – Name of the attribute to add.
  • *trait – 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)[source]

Adds a trait category to a class.

classmethod set_trait_dispatch_handler(name, klass, override=False)[source]

Sets a trait notification dispatch handler.

classmethod trait_subclasses(all=False)[source]

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)[source]

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.

trait_get(*names, **metadata)[source]

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)[source]

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.

trait_set(trait_change_notify=True, **traits)[source]

Shortcut for setting object trait attributes.

Parameters:
  • 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)
  • **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 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)[source]

Shortcut for setting object trait attributes.

Parameters:
  • 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)
  • **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 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
trait_setq(**traits)[source]

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)[source]

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 reset, 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)[source]

Returns the list of trait names to copy or clone by default.

all_trait_names()[source]

Returns the list of all trait names, including implicitly defined traits.

copy_traits(other, traits=None, memo=None, copy=None, **metadata)[source]

Copies another object’s trait attributes into this one.

Parameters:
  • other (object) – The object whose trait attribute values should be copied.
  • 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.
  • memo (dict) – A dictionary of objects that have already been copied.
  • 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 (list 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)[source]

Clones a new object from this one, optionally copying only a specified set of traits.

Parameters:
  • traits (list of strings) – The list of names of the trait attributes to copy.
  • memo (dict) – A dictionary of objects that have already been copied.
  • 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='', scrollable=None, **args)[source]

Displays a user interface window for editing trait attribute values.

Parameters:
  • 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 reference to the view object. If this attribute is not specified, the View object returned by trait_view() is used.
  • parent (toolkit control) – The reference to a user interface component to use as the parent window for the object’s UI window.
  • 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.
  • 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 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()[source]

Returns the default context to use for editing or configuring traits.

trait_view(name=None, view_element=None)[source]

Gets or sets a ViewElement associated with an object’s class.

Parameters:
  • name (str) – Name of a view element
  • 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()[source]

Returns the name of the default traits view for the object’s class.

classmethod class_default_traits_view()[source]

Returns the name of the default traits view for the class.

trait_views(klass=None)[source]

Returns a list of the names of all view elements associated with the current object’s class.

Parameters:klass (class) –

A class, such that all returned names must correspond to instances of this class. Possible values include:

  • Group
  • Item
  • View
  • 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()[source]

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.

classmethod class_trait_view_elements()[source]

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, handler=None, id='', scrollable=None, **args)[source]

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 representation of the current object. When this parameter is specified, the method reads the corresponding 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 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 existing 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 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:

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.

editable_traits()[source]

Returns an alphabetically sorted list of the names of non-event trait attributes associated with the current object.

classmethod class_editable_traits()[source]

Returns an alphabetically sorted list of the names of non-event trait attributes associated with the current class.

visible_traits()[source]

Returns an alphabetically sorted list of the names of non-event trait attributes associated with the current object, that should be GUI visible

classmethod class_visible_traits()[source]

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)[source]

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 information.
on_trait_change(handler, name=None, remove=False, dispatch='same', priority=False, deferred=False, target=None)[source]

Causes the object to invoke a handler whenever a trait attribute matching a specified pattern is modified, or removes the association.

Parameters:
  • handler (function) – A trait notification function for the name trait attribute, with one of the signatures described below.
  • 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.
  • remove (bool) – If True, removes the previously-set association between handler and name; if False (the default), creates the association.
  • dispatch (str) –

    A string indicating the thread on which notifications must be run. Possible 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 queue.
    fast_ui 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:

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
item1.item2 means item1 is a trait containing an object (or objects if item1 is a list or dict) with a trait called item2. Changes to either item1 or item2 cause a notification to be generated.
item1:item2 means item1 is a trait containing an object (or objects if item1 is a list or dict) with a trait called item2. Changes to item2 cause a notification to be generated, while changes to item1 do not (i.e., the ‘:’ indicates that changes to the link object should not be reported).
[ item1, item2, ..., itemN ] A list which matches any of the specified items. Note that at the topmost level, the surrounding square brackets are optional.
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.
prefix+ 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+metadata_name Matches any trait on the object whose name begins with prefix and which has metadata_name metadata.
prefix-metadata_name Matches 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','baz'] Equivalent to ‘foo,bar,baz’, but may be more useful in cases where the individual items are computed.
foo.bar.baz 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:baz Listen for changes to object.foo.bar.baz, and only report changes to object.foo.bar.baz.
foo.[bar,baz] Listen for trait changes to object.foo.bar and object.foo.baz.
[left,right]*.name Listen for 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,-dirty] Listen 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 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, 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 processed. 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 information 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:

  • object: object.foo
  • name: bar
  • old: old value for object.foo.bar
  • new: 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:

  • object: object.foo
  • name: bar_items
  • old: Undefined
  • new: 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 1 also has the special characteristic that if a final trait is a List or Dict, it will automatically 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.

on_trait_event(handler, name=None, remove=False, dispatch='same', priority=False, deferred=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:
  • handler (function) – A trait notification function for the name trait attribute, with one of the signatures described below.
  • 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.
  • remove (bool) – If True, removes the previously-set association between handler and name; if False (the default), creates the association.
  • dispatch (str) –

    A string indicating the thread on which notifications must be run. Possible 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 queue.
    fast_ui 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:

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
item1.item2 means item1 is a trait containing an object (or objects if item1 is a list or dict) with a trait called item2. Changes to either item1 or item2 cause a notification to be generated.
item1:item2 means item1 is a trait containing an object (or objects if item1 is a list or dict) with a trait called item2. Changes to item2 cause a notification to be generated, while changes to item1 do not (i.e., the ‘:’ indicates that changes to the link object should not be reported).
[ item1, item2, ..., itemN ] A list which matches any of the specified items. Note that at the topmost level, the surrounding square brackets are optional.
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.
prefix+ 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+metadata_name Matches any trait on the object whose name begins with prefix and which has metadata_name metadata.
prefix-metadata_name Matches 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','baz'] Equivalent to ‘foo,bar,baz’, but may be more useful in cases where the individual items are computed.
foo.bar.baz 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:baz Listen for changes to object.foo.bar.baz, and only report changes to object.foo.bar.baz.
foo.[bar,baz] Listen for trait changes to object.foo.bar and object.foo.baz.
[left,right]*.name Listen for 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,-dirty] Listen 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 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, 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 processed. 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 information 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:

  • object: object.foo
  • name: bar
  • old: old value for object.foo.bar
  • new: 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:

  • object: object.foo
  • name: bar_items
  • old: Undefined
  • new: 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 1 also has the special characteristic that if a final trait is a List or Dict, it will automatically 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_name, object, alias=None, mutual=True, remove=False)[source]

Synchronizes the value of a trait attribute on this object with a trait attribute on another object.

Parameters:
  • name (str) – Name of the trait attribute on this object.
  • object (object) – The object with which to synchronize.
  • alias (str) – Name of the trait attribute on other; if None or omitted, same as name.
  • mutual (bool or int) – Indicates whether synchronization is mutual (True or non-zero) or one-way (False or zero)
  • remove (bool or int) – Indicates whether synchronization is being added (False or zero) or removed (True or non-zero)

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)[source]

Adds a trait attribute to this object.

Parameters:
  • name (str) – Name of the attribute to add.
  • *trait – 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)[source]

Removes a trait attribute from this object.

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)[source]

Returns the trait definition for the name trait attribute.

Parameters:
  • name (str) – Name of the attribute whose trait definition is to be returned.
  • force (bool) – Indicates whether to return a trait definition if name is not explicitly defined.
  • 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)[source]

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 that attribute’s trait as the result.

validate_trait(name, value)[source]

Validates whether a value is legal for a trait.

Returns the validated value if it is valid.

traits(**metadata)[source]

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 expressions 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.

classmethod class_traits(**metadata)[source]

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 expressions 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)[source]

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.

classmethod class_trait_names(**metadata)[source]

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[source]

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[source]

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 ‘_’) 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[source]

Singleton class that support trait attributes.

class traits.has_traits.SingletonHasStrictTraits[source]

Singleton class that supports strict trait attributes.

Non-trait attributes generate an exception.

class traits.has_traits.SingletonHasPrivateTraits[source]

Singleton class that supports trait attributes, with private attributes being unchecked.

class traits.has_traits.Vetoable[source]

Defines a ‘vetoable’ request object and an associated event.

class traits.has_traits.Interface[source]

The base class for all interfaces.

class traits.has_traits.ISerializable[source]

A class that implemented ISerializable requires that all HasTraits objects saved as part of its state also implement ISerializable.

class traits.has_traits.traits_super[source]

ABC classes

Note

These classes are only available when the abc module is present.

class traits.has_traits.ABCMetaHasTraits[source]

A MetaHasTraits subclass which also inherits from abc.ABCMeta.

Note

The ABCMeta class is cooperative and behaves nicely with MetaHasTraits, provided it is inherited first.

class traits.has_traits.ABCHasTraits[source]

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[source]

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)[source]

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 all 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)[source]

Returns the correct ‘delegate’ listener pattern for a specified name and delegate trait.

traits.has_traits.implements(*interfaces)[source]

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.

Deprecated since version 4.4: Use the provides class decorator instead.

traits.has_traits.on_trait_change(name, post_init=False, dispatch='same')[source]

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 argument and the semantics of the dispatch keyword argument.

A handler defined using this decorator is normally effective immediately. However, if post_init is True, then the handler only becomes 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)[source]

Marks the following method definition as being a “cached property” that depends on the specified extended trait names. 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 @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_name = File
file_contents = Property

@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, the cached value _file_contents, which is maintained by the @cached_property wrapper code, is returned.

traits.has_traits.provides(*protocols)[source]

Class decorator to declare the protocols that a class provides.

Parameters:*protocols – A list of protocols (Interface classes or Python ABCs) that the decorated class provides.
traits.has_traits.weak_arg(arg)[source]

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.