traits.trait_handlers Module

Defines a standard set of TraitHandler subclasses.

A trait handler mediates the assignment of values to object traits. It verifies (via its validate() method) that a specified value is consistent with the object trait, and generates a TraitError exception if it is not consistent.

Classes

class traits.trait_handlers.TraitCoerceType(aType)[source]

Ensures that a value assigned to a trait attribute is of a specified Python type, or can be coerced to the specified type.

TraitCoerceType is the underlying handler for the predefined traits and factories for Python simple types. The TraitCoerceType class is also an example of a parametrized type, because the single TraitCoerceType class allows creating instances that check for totally different sets of values. For example:

class Person(HasTraits):
    name = Trait('', TraitCoerceType(''))
    weight = Trait(0.0, TraitCoerceType(float))

In this example, the name attribute must be of type str (string), while the weight attribute must be of type float, although both are based on instances of the TraitCoerceType class. Note that this example is essentially the same as writing:

class Person(HasTraits):
    name = Trait('')
    weight = Trait(0.0)

This simpler form is automatically changed by the Trait() function into the first form, based on TraitCoerceType instances, when the trait attributes are defined.

For attributes based on TraitCoerceType instances, if a value that is assigned is not of the type defined for the trait, a TraitError exception is raised. However, in certain cases, if the value can be coerced to the required type, then the coerced value is assigned to the attribute. Only widening coercions are allowed, to avoid any possible loss of precision. The following table lists the allowed coercions.

Trait Type

Coercible Types

complex

float, int

float

int

Parameters:

aType (type or object) – Either a Python type or a Python value. If this is an object, it is mapped to its corresponding type. For example, the string ‘cat’ is automatically mapped to str.

aType

A Python type to coerce values to.

Type:

type

validate(object, name, value)[source]

Verifies whether a new value assigned to a trait attribute is valid.

This method must be implemented by subclasses of TraitHandler. It is called whenever a new value is assigned to a trait attribute defined using this trait handler.

If the value received by validate() is not valid for the trait attribute, the method must called the predefined error() method to raise a TraitError exception

Parameters:
  • object (HasTraits instance) – The object whose attribute is being assigned.

  • name (str) – The name of the attribute being assigned.

  • value (any) – The proposed new value for the attribute.

Returns:

If the new value is valid, this method must return either the original value passed to it, or an alternate value to be assigned in place of the original value. Whatever value this method returns is the actual value assigned to object.name.

Return type:

any

info()[source]

Must return a string describing the type of value accepted by the trait handler.

The string should be a phrase describing the type defined by the TraitHandler subclass, rather than a complete sentence. For example, use the phrase, “a square sprocket” instead of the sentence, “The value must be a square sprocket.” The value returned by info() is combined with other information whenever an error occurs and therefore makes more sense to the user if the result is a phrase. The info() method is similar in purpose and use to the info attribute of a validator function.

Note that the result can include information specific to the particular trait handler instance. If the info() method is not overridden, the default method returns the value of the ‘info_text’ attribute.

get_editor(trait)[source]

Returns a trait editor that allows the user to modify the trait trait. This method only needs to be specified if traits defined using this trait handler require a non-default trait editor in trait user interfaces. The default implementation of this method returns a trait editor that allows the user to type an arbitrary string as the value.

For more information on trait user interfaces, refer to the Traits UI User Guide.

Parameters:

trait (Trait) – The trait to be edited.

class traits.trait_handlers.TraitCastType(aType)[source]

Ensures that a value assigned to a trait attribute is of a specified Python type, or can be cast to the specified type.

This class is similar to TraitCoerceType, but uses casting rather than coercion. Values are cast by calling the type with the value to be assigned as an argument. When casting is performed, the result of the cast is the value assigned to the trait attribute.

Any trait that uses a TraitCastType instance in its definition ensures that its value is of the type associated with the TraitCastType instance. For example:

class Person(HasTraits):
    name = Trait('', TraitCastType(''))
    weight = Trait(0.0, TraitCastType(float))

In this example, the name trait must be of type str (string), while the weight trait must be of type float. Note that this example is essentially the same as writing:

class Person(HasTraits):
    name = CStr
    weight = CFloat

To understand the difference between TraitCoerceType and TraitCastType (and also between Float and CFloat), consider the following example:

>>> class Person(HasTraits):
...     weight = Float
...     cweight = CFloat
...
>>> bill = Person()
>>> bill.weight = 180    # OK, coerced to 180.0
>>> bill.cweight = 180   # OK, cast to 180.0
>>> bill.weight = '180'  # Error, invalid coercion
>>> bill.cweight = '180' # OK, cast to float('180')
Parameters:

aType (type) – Either a Python type or a Python value. If this is an object, it is mapped to its corresponding type. For example, the string ‘cat’ is automatically mapped to str.

aType

A Python type to cast values to.

Type:

type

validate(object, name, value)[source]

Verifies whether a new value assigned to a trait attribute is valid.

This method must be implemented by subclasses of TraitHandler. It is called whenever a new value is assigned to a trait attribute defined using this trait handler.

If the value received by validate() is not valid for the trait attribute, the method must called the predefined error() method to raise a TraitError exception

Parameters:
  • object (HasTraits instance) – The object whose attribute is being assigned.

  • name (str) – The name of the attribute being assigned.

  • value (any) – The proposed new value for the attribute.

Returns:

If the new value is valid, this method must return either the original value passed to it, or an alternate value to be assigned in place of the original value. Whatever value this method returns is the actual value assigned to object.name.

Return type:

any

class traits.trait_handlers.TraitInstance(aClass, allow_none=True, module='')[source]

Ensures that trait attribute values belong to a specified Python type.

Any trait that uses a TraitInstance handler ensures that its values belong to the specified type or class (or one of its subclasses). For example:

class Employee(HasTraits):
    manager = Trait(None, TraitInstance(Employee, True))

This example defines a class Employee, which has a manager trait attribute, which accepts either None or an instance of Employee as its value.

TraitInstance ensures that assigned values are exactly of the type specified (i.e., no coercion is performed).

Parameters:
  • aClass (type, object or str) – A Python type or a string that identifies the type, or an object. If this is an object, it is mapped to the class it is an instance of. If this is a str, it is either the name of a class in the module identified by the module parameter, or an identifier of the form “module_name*[.*module_name….].*class_name*”.

  • allow_none (bool) – Flag indicating whether None is accepted as a valid value.

  • module (str) – The name of the module that the class belongs to. This is ignored if the type is provided directly, or the str value is an identifier with ‘.’s in it.

aClass

A Python type, or a string which identifies the type. If this is a str, it is either the name of a class in the module identified by the module attribute, or an identifier of the form “module_name*[.*module_name….].*class_name*”. A string value will be replaced by the actual type object the first time the trait is used to validate an object.

Type:

type or str

module

The name of the module that the class belongs to. This is ignored if the type is provided directly, or the str value is an identifier with ‘.’s in it.

Type:

str

allow_none()[source]

Whether or not None is permitted as a valid value.

Returns:

Whether or not None is a valid value.

Return type:

bool

validate(object, name, value)[source]

Verifies whether a new value assigned to a trait attribute is valid.

This method must be implemented by subclasses of TraitHandler. It is called whenever a new value is assigned to a trait attribute defined using this trait handler.

If the value received by validate() is not valid for the trait attribute, the method must called the predefined error() method to raise a TraitError exception

Parameters:
  • object (HasTraits instance) – The object whose attribute is being assigned.

  • name (str) – The name of the attribute being assigned.

  • value (any) – The proposed new value for the attribute.

Returns:

If the new value is valid, this method must return either the original value passed to it, or an alternate value to be assigned in place of the original value. Whatever value this method returns is the actual value assigned to object.name.

Return type:

any

info()[source]

Must return a string describing the type of value accepted by the trait handler.

The string should be a phrase describing the type defined by the TraitHandler subclass, rather than a complete sentence. For example, use the phrase, “a square sprocket” instead of the sentence, “The value must be a square sprocket.” The value returned by info() is combined with other information whenever an error occurs and therefore makes more sense to the user if the result is a phrase. The info() method is similar in purpose and use to the info attribute of a validator function.

Note that the result can include information specific to the particular trait handler instance. If the info() method is not overridden, the default method returns the value of the ‘info_text’ attribute.

get_editor(trait)[source]

Returns a trait editor that allows the user to modify the trait trait. This method only needs to be specified if traits defined using this trait handler require a non-default trait editor in trait user interfaces. The default implementation of this method returns a trait editor that allows the user to type an arbitrary string as the value.

For more information on trait user interfaces, refer to the Traits UI User Guide.

Parameters:

trait (Trait) – The trait to be edited.

class traits.trait_handlers.TraitFunction(aFunc)[source]

Ensures that assigned trait attribute values are acceptable to a specified validator function.

TraitFunction is the underlying handler for the predefined trait Function, and for the use of function references as arguments to the Trait() function.

The signature of the function must be of the form function*(*object, name, value). The function must verify that value is a legal value for the name trait attribute of object. If it is, the value returned by the function is the actual value assigned to the trait attribute. If it is not, the function must raise a TraitError exception.

Parameters:

aFunc (function) – A function to validate trait attribute values.

aFunc

A function to validate trait attribute values.

Type:

function

validate(object, name, value)[source]

Verifies whether a new value assigned to a trait attribute is valid.

This method must be implemented by subclasses of TraitHandler. It is called whenever a new value is assigned to a trait attribute defined using this trait handler.

If the value received by validate() is not valid for the trait attribute, the method must called the predefined error() method to raise a TraitError exception

Parameters:
  • object (HasTraits instance) – The object whose attribute is being assigned.

  • name (str) – The name of the attribute being assigned.

  • value (any) – The proposed new value for the attribute.

Returns:

If the new value is valid, this method must return either the original value passed to it, or an alternate value to be assigned in place of the original value. Whatever value this method returns is the actual value assigned to object.name.

Return type:

any

info()[source]

Must return a string describing the type of value accepted by the trait handler.

The string should be a phrase describing the type defined by the TraitHandler subclass, rather than a complete sentence. For example, use the phrase, “a square sprocket” instead of the sentence, “The value must be a square sprocket.” The value returned by info() is combined with other information whenever an error occurs and therefore makes more sense to the user if the result is a phrase. The info() method is similar in purpose and use to the info attribute of a validator function.

Note that the result can include information specific to the particular trait handler instance. If the info() method is not overridden, the default method returns the value of the ‘info_text’ attribute.

class traits.trait_handlers.TraitEnum(*values)[source]

Ensures that a value assigned to a trait attribute is a member of a specified list of values.

TraitEnum is the underlying handler for the forms of the Trait() function that take a list of possible values

The list of legal values can be provided as a list or tuple of values. That is, TraitEnum([1, 2, 3]), TraitEnum((1, 2, 3)) and TraitEnum(1, 2, 3) are equivalent. For example:

class Flower(HasTraits):
    color = Trait('white', TraitEnum(['white', 'yellow', 'red']))
    kind  = Trait('annual', TraitEnum('annual', 'perennial'))

This example defines a Flower class, which has a color trait attribute, which can have as its value, one of the three strings, ‘white’, ‘yellow’, or ‘red’, and a kind trait attribute, which can have as its value, either of the strings ‘annual’ or ‘perennial’. This is equivalent to the following class definition:

class Flower(HasTraits):
    color = Trait(['white', 'yellow', 'red'])
    kind  = Trait('annual', 'perennial')

The Trait() function automatically maps traits of the form shown in this example to the form shown in the preceding example whenever it encounters them in a trait definition.

Parameters:

*values – Either all legal values for the enumeration, or a single list or tuple of the legal values.

values

Enumeration of all legal values for a trait.

Type:

tuple

validate(object, name, value)[source]

Verifies whether a new value assigned to a trait attribute is valid.

This method must be implemented by subclasses of TraitHandler. It is called whenever a new value is assigned to a trait attribute defined using this trait handler.

If the value received by validate() is not valid for the trait attribute, the method must called the predefined error() method to raise a TraitError exception

Parameters:
  • object (HasTraits instance) – The object whose attribute is being assigned.

  • name (str) – The name of the attribute being assigned.

  • value (any) – The proposed new value for the attribute.

Returns:

If the new value is valid, this method must return either the original value passed to it, or an alternate value to be assigned in place of the original value. Whatever value this method returns is the actual value assigned to object.name.

Return type:

any

info()[source]

Must return a string describing the type of value accepted by the trait handler.

The string should be a phrase describing the type defined by the TraitHandler subclass, rather than a complete sentence. For example, use the phrase, “a square sprocket” instead of the sentence, “The value must be a square sprocket.” The value returned by info() is combined with other information whenever an error occurs and therefore makes more sense to the user if the result is a phrase. The info() method is similar in purpose and use to the info attribute of a validator function.

Note that the result can include information specific to the particular trait handler instance. If the info() method is not overridden, the default method returns the value of the ‘info_text’ attribute.

get_editor(trait)[source]

Returns a trait editor that allows the user to modify the trait trait. This method only needs to be specified if traits defined using this trait handler require a non-default trait editor in trait user interfaces. The default implementation of this method returns a trait editor that allows the user to type an arbitrary string as the value.

For more information on trait user interfaces, refer to the Traits UI User Guide.

Parameters:

trait (Trait) – The trait to be edited.

class traits.trait_handlers.TraitCompound(*handlers)[source]

Provides a logical-OR combination of other trait handlers.

This class provides a means of creating complex trait definitions by combining several simpler trait definitions. TraitCompound is the underlying handler for the general forms of the Trait() function.

A value is a valid value for a trait attribute based on a TraitCompound instance if the value is valid for at least one of the TraitHandler or trait objects supplied to the constructor. In addition, if at least one of the TraitHandler or trait objects is mapped (e.g., based on a TraitMap instance), then the TraitCompound is also mapped. In this case, any non-mapped traits or trait handlers use identity mapping.

Parameters:

*handlers – Either all TraitHandlers or trait objects to be combined, or a single list or tuple of TraitHandlers or trait objects.

handlers

A list or tuple of TraitHandler or trait objects to be combined.

Type:

list or tuple

validate(object, name, value)[source]

Verifies whether a new value assigned to a trait attribute is valid.

This method must be implemented by subclasses of TraitHandler. It is called whenever a new value is assigned to a trait attribute defined using this trait handler.

If the value received by validate() is not valid for the trait attribute, the method must called the predefined error() method to raise a TraitError exception

Parameters:
  • object (HasTraits instance) – The object whose attribute is being assigned.

  • name (str) – The name of the attribute being assigned.

  • value (any) – The proposed new value for the attribute.

Returns:

If the new value is valid, this method must return either the original value passed to it, or an alternate value to be assigned in place of the original value. Whatever value this method returns is the actual value assigned to object.name.

Return type:

any

full_info(object, name, value)[source]

Returns a string describing the type of value accepted by the trait handler.

The string should be a phrase describing the type defined by the TraitHandler subclass, rather than a complete sentence. For example, use the phrase, “a square sprocket” instead of the sentence, “The value must be a square sprocket.” The value returned by full_info() is combined with other information whenever an error occurs and therefore makes more sense to the user if the result is a phrase. The full_info() method is similar in purpose and use to the info attribute of a validator function.

Note that the result can include information specific to the particular trait handler instance. If the full_info() method is not overridden, the default method returns the value of calling the info() method.

Parameters:
  • object (object) – The object whose attribute is being assigned.

  • name (str) – The name of the attribute being assigned.

  • value – The proposed new value for the attribute.

info()[source]

Must return a string describing the type of value accepted by the trait handler.

The string should be a phrase describing the type defined by the TraitHandler subclass, rather than a complete sentence. For example, use the phrase, “a square sprocket” instead of the sentence, “The value must be a square sprocket.” The value returned by info() is combined with other information whenever an error occurs and therefore makes more sense to the user if the result is a phrase. The info() method is similar in purpose and use to the info attribute of a validator function.

Note that the result can include information specific to the particular trait handler instance. If the info() method is not overridden, the default method returns the value of the ‘info_text’ attribute.

get_editor(trait)[source]

Returns a trait editor that allows the user to modify the trait trait. This method only needs to be specified if traits defined using this trait handler require a non-default trait editor in trait user interfaces. The default implementation of this method returns a trait editor that allows the user to type an arbitrary string as the value.

For more information on trait user interfaces, refer to the Traits UI User Guide.

Parameters:

trait (Trait) – The trait to be edited.

class traits.trait_handlers.TraitMap(map)[source]

Checks that the value assigned to a trait attribute is a key of a specified dictionary, and also assigns the dictionary value corresponding to that key to a shadow attribute.

A trait attribute that uses a TraitMap handler is called mapped trait attribute. In practice, this means that the resulting object actually contains two attributes: one whose value is a key of the TraitMap dictionary, and the other whose value is the corresponding value of the TraitMap dictionary. The name of the shadow attribute is simply the base attribute name with an underscore (‘_’) appended. Mapped trait attributes can be used to allow a variety of user-friendly input values to be mapped to a set of internal, program-friendly values.

Example

The following example defines a Person class:

>>> class Person(HasTraits):
...     married = Trait('yes', TraitMap({'yes': 1, 'no': 0})
...
>>> bob = Person()
>>> print bob.married
yes
>>> print bob.married_
1

In this example, the default value of the married attribute of the Person class is ‘yes’. Because this attribute is defined using TraitMap, instances of Person have another attribute, married_, whose default value is 1, the dictionary value corresponding to the key ‘yes’.

Parameters:

map (dict) – A dictionary whose keys are valid values for the trait attribute, and whose corresponding values are the values for the shadow trait attribute.

map

A dictionary whose keys are valid values for the trait attribute, and whose corresponding values are the values for the shadow trait attribute.

Type:

dict

validate(object, name, value)[source]

Verifies whether a new value assigned to a trait attribute is valid.

This method must be implemented by subclasses of TraitHandler. It is called whenever a new value is assigned to a trait attribute defined using this trait handler.

If the value received by validate() is not valid for the trait attribute, the method must called the predefined error() method to raise a TraitError exception

Parameters:
  • object (HasTraits instance) – The object whose attribute is being assigned.

  • name (str) – The name of the attribute being assigned.

  • value (any) – The proposed new value for the attribute.

Returns:

If the new value is valid, this method must return either the original value passed to it, or an alternate value to be assigned in place of the original value. Whatever value this method returns is the actual value assigned to object.name.

Return type:

any

mapped_value(value)[source]

Get the mapped value for a value.

info()[source]

Must return a string describing the type of value accepted by the trait handler.

The string should be a phrase describing the type defined by the TraitHandler subclass, rather than a complete sentence. For example, use the phrase, “a square sprocket” instead of the sentence, “The value must be a square sprocket.” The value returned by info() is combined with other information whenever an error occurs and therefore makes more sense to the user if the result is a phrase. The info() method is similar in purpose and use to the info attribute of a validator function.

Note that the result can include information specific to the particular trait handler instance. If the info() method is not overridden, the default method returns the value of the ‘info_text’ attribute.

get_editor(trait)[source]

Returns a trait editor that allows the user to modify the trait trait. This method only needs to be specified if traits defined using this trait handler require a non-default trait editor in trait user interfaces. The default implementation of this method returns a trait editor that allows the user to type an arbitrary string as the value.

For more information on trait user interfaces, refer to the Traits UI User Guide.

Parameters:

trait (Trait) – The trait to be edited.

Private Functions

traits.trait_handlers._undefined_get(object, name)[source]
traits.trait_handlers._undefined_set(object, name, value)[source]