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 or TraitPrefixMap 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 TraitPrefixList, 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]

Deprecated Handlers

The following TraitHandler classes and instances are deprecated, and may be removed in a future version of Traits.

Deprecated since version 6.0.0.

class traits.trait_handlers.TraitDict(key_trait=None, value_trait=None, has_items=True)[source]

Ensures that values assigned to a trait attribute are dictionaries whose keys and values are of specified types.

TraitDict also makes sure that any changes to keys or values made that are made after the dictionary is assigned to the trait attribute satisfy the type constraints. TraitDict is the underlying handler for the dictionary-based predefined traits, and the Dict() trait factory.

Example

class WorkoutClass(HasTraits):
    member_weights = Trait({}, TraitDict(str, float))

This example defines a WorkoutClass class containing a member_weights trait attribute whose value must be a dictionary containing keys that are strings (i.e., the members’ names) and whose associated values must be floats (i.e., their most recently recorded weight).

Parameters
  • key_trait (trait) – The type for the dictionary keys. If this is None or omitted, the keys in the dictionary can be of any type. Otherwise, this must be either a trait, or a value that can be converted to a trait using the trait_from() function. In this case, all dictionary keys are checked to ensure that they are of the type specified.

  • value_trait (trait) – The type for the dictionary values. If this is None or omitted, the values in the dictionary can be of any type. Otherwise, this must be either a trait, or a value that can be converted to a trait using the trait_from() function. In this case, all dictionary values are checked to ensure that they are of the type specified.

  • has_items (bool) – Flag indicating whether the dictionary contains entries.

key_trait

The type for the dictionary keys. If this is None then the keys are not validated.

Type

CTrait or TraitHandler or None

value_trait

The type for the dictionary values. If this is None then the values are not validated.

Type

CTrait or TraitHandler or None

value_handler

The trait handler for the dictionary values.

Type

BaseTraitHandler or None

has_items

Flag indicating whether the dictionary contains entries.

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

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.

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.TraitList(trait=None, minlen=0, maxlen=9223372036854775807, has_items=True)[source]

Ensures that a value assigned to a trait attribute is a list containing elements of a specified type, and that the length of the list is also within a specified range.

TraitList also makes sure that any changes made to the list after it is assigned to the trait attribute do not violate the list’s type and length constraints. TraitList is the underlying handler for the predefined list-based traits.

Example

class Card(HasTraits):
    pass

class Hand(HasTraits):
    cards = Trait([], TraitList(Trait(Card), maxlen=52))

This example defines a Hand class, which has a cards trait attribute, which is a list of Card objects and can have from 0 to 52 items in the list.

Parameters
  • trait (Trait) – The type of items the list can contain. If this is None or omitted, then no type checking is performed on any items in the list; otherwise, this must be either a trait, or a value that can be converted to a trait using the trait_from() function.

  • minlen (int) – The minimum length of the list.

  • maxlen (int) – The maximum length of the list.

  • has_items (bool) – Flag indicating whether the list contains elements.

item_trait

The type of items the list can contain. If None, no type checking is performed on the items of the list.

Type

CTrait or None

minlen

The minimum length of the list.

Type

int

maxlen

The maximum length of the list.

Type

int

has_items

Flag indicating whether the list contains elements.

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

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.

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.TraitTuple(*args)[source]

Ensures that values assigned to a trait attribute are tuples of a specified length, with elements that are of specified types.

TraitTuple is the underlying handler for the predefined trait Tuple, and the trait factory Tuple().

Example

The following example defines a Card class:

rank = Range(1, 13)
suit = Trait('Hearts', 'Diamonds', 'Spades', 'Clubs')
class Card(HasTraits):
    value = Trait(TraitTuple(rank, suit))

The Card class has a value trait attribute, which must be a tuple of two elments. The first element must be an integer in the range from 1 to 13, and the second element must be one of the four strings, ‘Hearts’, ‘Diamonds’, ‘Spades’, or ‘Clubs’.

Parameters
  • *args – The traits, each traiti specifies the type that the ith element of a tuple must be. Each traiti must be either a trait, or a value that can be converted to a trait using the trait_from() function. The resulting trait handler accepts values that are tuples of the same length as args, and whose ith element is of the type specified by traiti.

  • types (tuple of CTrait instances) – The traits to use for each item in a validated 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.

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.

Deprecated since version 6.1.0.

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

Ensures that a value assigned to a trait attribute is a member of a list of specified string values, or is a unique prefix of one of those values.

Deprecated since version 6.1: TraitPrefixList is scheduled for removal in Traits 7.0. Use the PrefixList trait type instead.

TraitPrefixList is a variation on TraitEnum. The values that can be assigned to a trait attribute defined using a TraitPrefixList handler is the set of all strings supplied to the TraitPrefixList constructor, as well as any unique prefix of those strings. That is, if the set of strings supplied to the constructor is described by [s1, s2, …, sn], then the string v is a valid value for the trait if v == si[:j] for one and only one pair of values (i, j). If v is a valid value, then the actual value assigned to the trait attribute is the corresponding si value that v matched.

As with TraitEnum, the list of legal values can be provided as a list or tuple of values. That is, TraitPrefixList(['one', 'two', 'three']) and TraitPrefixList('one', 'two', 'three') are equivalent.

Example

class Person(HasTraits):
    married = Trait('no', TraitPrefixList('yes', 'no')

The Person class has a married trait that accepts any of the strings ‘y’, ‘ye’, ‘yes’, ‘n’, or ‘no’ as valid values. However, the actual values assigned as the value of the trait attribute are limited to either ‘yes’ or ‘no’. That is, if the value ‘y’ is assigned to the married attribute, the actual value assigned will be ‘yes’.

Note that the algorithm used by TraitPrefixList in determining whether a string is a valid value is fairly efficient in terms of both time and space, and is not based on a brute force set of comparisons.

Parameters

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

values

Enumeration of all legal values for a trait.

Type

tuple of strings

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.TraitPrefixMap(map)[source]

A cross between the TraitPrefixList and TraitMap classes.

Deprecated since version 6.1: TraitPrefixMap is scheduled for removal in Traits 7.0. Use the PrefixMap trait type instead.

Like TraitMap, TraitPrefixMap is created using a dictionary, but in this case, the keys of the dictionary must be strings. Like TraitPrefixList, a string v is a valid value for the trait attribute if it is a prefix of one and only one key k in the dictionary. The actual values assigned to the trait attribute is k, and its corresponding mapped attribute is map*[*k].

Example

mapping = {'true': 1, 'yes': 1, 'false': 0, 'no': 0 }
boolean_map = Trait('true', TraitPrefixMap(mapping))

This example defines a Boolean trait that accepts any prefix of ‘true’, ‘yes’, ‘false’, or ‘no’, and maps them to 1 or 0.

Parameters

map (dict) – A dictionary whose keys are strings that 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 strings that 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

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.