traits.has_traits Module

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

Classes

class traits.has_traits.MetaHasTraits(class_name, bases, class_dict)[source]

Controls the creation of HasTraits classes.

The heavy work is done by the update_traits_class_dict function, which takes the class_dict dictionary of class members and extracts and processes the trait declarations in it. The trait declarations are then added back to the class dictionary and passed off to the __new__ method of the type superclass, to be added to the class.

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.

Deprecated since version 6.3.0.

classmethod remove_listener(listener, class_name='')[source]

Removes a class creation listener.

Deprecated since version 6.3.0.

class traits.has_traits.MetaInterface(name, bases, namespace, **kwargs)[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__(*args, **kwargs)
__call__(adaptee, default=<class 'traits.adaptation.adaptation_error.AdaptationError'>)[source]

Attempt to adapt the adaptee to this interface.

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

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.

Subclass should avoid defining new traits and/or methods with names starting with “trait” or “_trait” to avoid overshadowing existing methods, unless it has been documented as being safe to do so.

wrappers =
{‘same’: TraitChangeNotifyWrapper,
‘extended’: ExtendedTraitChangeNotifyWrapper,
‘new’: NewTraitChangeNotifyWrapper,
‘fast_ui’: FastUITraitChangeNotifyWrapper,
‘ui’: FastUITraitChangeNotifyWrapper}

Mapping from dispatch type to notification wrapper class type

trait_added = Event(Str())

An event fired when a new trait is dynamically added to the object. The value is the name of the trait that was added.

trait_modified = Event()

An event that can be fired to indicate that the state of the object has been modified.

classmethod add_class_trait(name, *trait)[source]

Adds a named trait attribute to this class.

Also adds the same attribute to all subclasses.

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

Tests whether the object implements one or more of the interfaces specified by interfaces. Return True if it does, and False otherwise.

Parameters:

*interfaces – One or more traits Interface (sub)classes.

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

Retrieve trait values for one or more traits.

This function can be called in one of three ways. In the first form, the user passes the names of one or more traits to be retrieved:

my_object.trait_get("trait_name1", "trait_name2")

In the second form, the user passes a list of zero or more names of traits:

my_object.trait_get(["trait_name1", "trait_name2"])

In the final form, no trait names are passed, and all trait names and trait values are returned, subject to the given metadata filters:

my_object.trait_get(transient=True, frombicated=False)

In all cases, a dictionary mapping trait names to trait values is returned.

For the first two forms, if any name does not correspond to a defined trait, it is not included in the result.

Parameters:
  • *names – Names of the traits to look up, or a single positional argument providing a sequence of trait names.

  • **metadata – Metadata information used to filter the traits to return. This information is used only when no names are provided.

Returns:

result – A dictionary mapping the selected trait names to their corresponding values.

Return type:

dict

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

Retrieve trait values for one or more traits.

This function can be called in one of three ways. In the first form, the user passes the names of one or more traits to be retrieved:

my_object.trait_get("trait_name1", "trait_name2")

In the second form, the user passes a list of zero or more names of traits:

my_object.trait_get(["trait_name1", "trait_name2"])

In the final form, no trait names are passed, and all trait names and trait values are returned, subject to the given metadata filters:

my_object.trait_get(transient=True, frombicated=False)

In all cases, a dictionary mapping trait names to trait values is returned.

For the first two forms, if any name does not correspond to a defined trait, it is not included in the result.

Parameters:
  • *names – Names of the traits to look up, or a single positional argument providing a sequence of trait names.

  • **metadata – Metadata information used to filter the traits to return. This information is used only when no names are provided.

Returns:

result – A dictionary mapping the selected trait names to their corresponding values.

Return type:

dict

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

Shortcut for setting object trait attributes.

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
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:

The method returns this object, after setting attributes.

Return type:

self

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

Shortcut for setting object trait attributes.

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
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:

The method returns this object, after setting attributes.

Return type:

self

trait_setq(**traits)[source]

Shortcut for setting object trait attributes.

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
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:

The method returns this object, after setting attributes.

Return type:

self

reset_traits(traits=None, **metadata)[source]

Resets some or all of an object’s trait attributes to their default values.

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.

Parameters:

traits (list of strings) – Names of trait attributes to reset.

Returns:

unresetable – A list of attributes that the method was unable to reset, which is empty if all the attributes were successfully reset.

Return type:

list of strings

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 – A list of attributes that the method was unable to copy, which is empty if all the attributes were successfully copied.

Return type:

list of strings

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.

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.

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:

The newly cloned object.

Return type:

new

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.

Return type:

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.

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.

Parameters:
  • name (str) – Name of a view element

  • view_element (ViewElement) – View element to associate

Return type:

A view element.

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.

If klass is specified, the list of names is filtered such that only objects that are instances of the specified class are returned.

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

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=None, 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.

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.

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.

    Deprecated since version 6.0.0.

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

    Deprecated since version 6.2.0.

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

Return type:

True on success.

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.

observe(handler, expression, *, remove=False, dispatch='same')[source]

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

The expression parameter can be a single string or an Expression object. A list of expressions is also accepted.

When expression is a string, its content should follow Traits Mini Language semantics:

Expression

Meaning

item1.item2

Observes trait item2 on the object under trait item1. Changes to either item1 or item2 cause a notification to be fired.

item1:item2

Similar to the above, except changes to item1 will not fire events (the ‘:’ indicates no notifications).

[item1, item2, ..., itemN]

A list which matches any of the specified items. Each item can itself be an expression.

items

Special keyword for observing a trait named items or items inside a list / dict / set.

+metadata_name

Matches any trait on the object having metadata_name metadata.

All spaces will be ignored.

The ObserverExpression object supports the above features and more.

Parameters:
  • handler (callable(event)) – A callable that will be invoked when the observed trait changes. It must accept one argument, which is an event object providing information about the change. See traits.observation.events for details.

  • expression (str or list or ObserverExpression) – A description of what traits are being observed. If this is a list, each item must be a string or an Expression.

  • remove (boolean, optional) – Whether to remove the event handler. Default is to add the event handler.

  • dispatch (str, optional) –

    A string indicating how the handler should be run. Default is to run on the same thread where the change occurs.

    Possible values are:

    value

    dispatch

    same

    Run notifications on the same thread where the change occurs. The notifications are executed immediately.

    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.

Raises:

NotifierNotFound – When attempting to remove a handler that doesn’t exist.

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.

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.

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.

See also

HasTraits.observe

A newer API for defining traits notifications.

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.

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.

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.

See also

HasTraits.observe

A newer API for defining traits notifications.

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.

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.

For List traits, the list’s items are also synchronized, so that mutations to this trait’s list will be reflected in the synchronized list (and vice versa in the case of mutual synchronization). For Dict and Set traits, items are not synchronized.

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)

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 – True if the trait was successfully removed.

Return type:

bool

trait(name, force=False, copy=False)[source]

Returns the trait definition for the name trait attribute.

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

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.

base_trait(name)[source]

Returns the base trait definition for a trait attribute.

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.

Parameters:

name (str) – Name of the attribute whose trait definition is returned.

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. Note that any traits with a name containing the suffix “_items” are always excluded.

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.

Parameters:

**metadata – Criteria for selecting trait attributes.

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.

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.

Parameters:

**metadata – Criteria for selecting trait attributes.

trait_names(**metadata)[source]

Returns a list of the names of all trait attributes whose definitions match the set of metadata criteria specified.

This method is similar to the traits() method, but returns only the names of the matching trait attributes, not the trait definitions.

Parameters:

**metadata – Criteria for selecting trait attributes.

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.

This method is similar to the traits() method, but returns only the names of the matching trait attributes, not the trait definitions.

Parameters:

**metadata – Criteria for selecting trait attributes.

add_trait_listener(object, prefix='')[source]

Add (Java-style) event listener to an object.

remove_trait_listener(object, prefix='')[source]

Remove (Java-style) event listener to an object.

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.HasRequiredTraits(**traits)[source]

This class builds on the functionality of HasStrictTraits and ensures that any object attribute with required=True in its metadata must be passed as an argument on object initialization.

This can be useful in cases where an object has traits which are required for it to function correctly.

Raises:

TraitError – If a required trait is not passed as an argument.

Examples

A class with required traits:

>>> class RequiredTest(HasRequiredTraits):
...     required_trait = Any(required=True)
...     non_required_trait = Any()

Creating an instance of a HasRequiredTraits subclass:

>>> test_instance = RequiredTest(required_trait=13, non_required_trait=11)
>>> test_instance2 = RequiredTest(required_trait=13)

Forgetting to specify a required trait:

>>> test_instance = RequiredTest(non_required_trait=11)
traits.trait_errors.TraitError: The following required traits were not
provided: required_trait.
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.Vetoable[source]

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

class traits.has_traits.Interface(adaptee, default=<class 'traits.adaptation.adaptation_error.AdaptationError'>)[source]

The base class for all interfaces.

class traits.has_traits.ISerializable(adaptee, default=<class 'traits.adaptation.adaptation_error.AdaptationError'>)[source]

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

ABC classes

Note

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

class traits.has_traits.ABCMetaHasTraits(name, bases, namespace, **kwargs)[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(observe='file_name')

@cached_property
def _get_file_contents(self):
    with open(self.file_name, 'rb') as fh:
        return fh.read()

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 observe 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.observe(expression, *, post_init=False, dispatch='same')[source]

Marks the wrapped method as being a handler to be called when the specified traits change.

This decorator can be stacked, e.g.:

@observe("attr1")
@observe("attr2", post_init=True)
def updated(self, event):
    ...

The decorated function must accept one argument which is the event object representing the change. See traits.observation.events for details.

Parameters:
  • expression (str or list or ObserverExpression) – A description of what traits are being observed. If this is a list, each item must be a string or Expression. See HasTraits.observe() for details on the semantics when passing a string.

  • post_init (boolean, optional) – Whether the change handler should be attached after the state is set when instantiating an object. Default is false, and values provided to the instance constructor will trigger the change handler to fire if the value is different from the default. Set to true to avoid this change event.

  • dispatch (str, optional) –

    A string indicating how the handler should be run. Default is to run it on the same thread where the change occurs. Possible values are:

    value

    dispatch

    same

    Run notifications on the same thread where the change occurs. The notifications are executed immediately.

    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.

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.

See also

observe

A newer API for defining traits notifications.

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):
    with open(self.file_name, 'rb') as fh:
        return fh.read()

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.

Deprecated Classes

The following HasTraits subclasses are deprecated, and may be removed in a future version of Traits.

class traits.has_traits.SingletonHasTraits(*args, **traits)[source]

Singleton class that support trait attributes.

class traits.has_traits.SingletonHasStrictTraits(*args, **traits)[source]

Singleton class that supports strict trait attributes.

Non-trait attributes generate an exception.

class traits.has_traits.SingletonHasPrivateTraits(*args, **traits)[source]

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