trait_handlers Module

Defines the BaseTraitHandler class and a standard set of BaseTraitHandler subclasses for use with the Traits package.

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

Classes

class traits.trait_handlers.BaseTraitHandler[source]

The task of this class and its subclasses is to verify the correctness of values assigned to object trait attributes.

This class is an alternative to trait validator functions. A trait handler has several advantages over a trait validator function, due to being an object:

  • Trait handlers have constructors and state. Therefore, you can use them to create parametrized types.
  • Trait handlers can have multiple methods, whereas validator functions can have only one callable interface. This feature allows more flexibility in their implementation, and allows them to handle a wider range of cases, such as interactions with other components.
error(object, name, value)[source]

Raises a TraitError exception.

Parameters:
  • object (object) – The object whose attribute is being assigned.
  • name (str) – The name of the attribute being assigned.
  • value (object) – The proposed new value for the attribute.

Description

This method is called by the validate() method when an assigned value is not valid. Raising a TraitError exception either notifies the user of the problem, or, in the case of compound traits, provides a chance for another trait handler to handle to validate the value.

full_info(object, name, value)[source]

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

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.

Description

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

Note that the result can include information specific to the particular trait handler instance. For example, TraitRange instances return a string indicating the range of values acceptable to the handler (e.g., “an integer in the range from 1 to 9”). If the full_info() method is not overridden, the default method returns the value of calling the info() method.

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. For example, TraitRange instances return a string indicating the range of values acceptable to the handler (e.g., “an integer in the range from 1 to 9”). If the info() method is not overridden, the default method returns the value of the ‘info_text’ attribute.

repr(value)[source]

Returns a printable representation of a value along with its type.

Deprecated since version 3.0.3: This functionality was only used to provide readable error messages. This functionality has been incorporated into TraitError itself.

Parameters:value (object) – The value to be printed.
get_editor(trait=None)[source]

Returns a trait editor that allows the user to modify the trait trait.

Parameters:trait (Trait) – The trait to be edited.

Description

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

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

create_editor()[source]

Returns the default traits UI editor to use for a trait.

inner_traits()[source]

Returns a tuple containing the inner traits for this trait. Most trait handlers do not have any inner traits, and so will return an empty tuple. The exceptions are List and Dict trait types, which have inner traits used to validate the values assigned to the trait. For example, in List( Int ), the inner traits for List are ( Int, ).

traits.trait_handlers.NoDefaultSpecified[source]
class traits.trait_handlers.TraitType(default_value=<traits.trait_handlers.NoDefaultSpecified object>, **metadata)[source]

Base class for new trait types.

This class enables you to define new traits using a class-based approach, instead of by calling the Trait() factory function with an instance of a TraitHandler derived object.

When subclassing this class, you can implement one or more of the method signatures below. Note that these methods are defined only as comments, because the absence of method definitions in the subclass definition implicitly provides information about how the trait should operate.

The optional methods are as follows:

  • get ( self, object, name ):

    This is the getter method of a trait that behaves like a property.

    Parameters:

    object (object) – The object that the property applies to.

    name (str) – The name of the property on object property.

    Description

    If neither this method nor the set() method is defined, the value of the trait is handled like a normal object attribute. If this method is not defined, but the set() method is defined, the trait behaves like a write-only property. This method should return the value of the name property for the object object.

  • set ( self, object, name, value )

    This is the setter method of a trait that behaves like a property.

    Parameters:

    object (object) – The object that the property applies to.

    name (str) – The name of the property on object.

    value – The value being assigned as the value of the property.

    Description

    If neither this method nor the get() method is implemented, the trait behaves like a normal trait attribute. If this method is not defined, but the get() method is defined, the trait behaves like a read-only property. This method does not need to return a value, but it should raise a TraitError exception if the specified value is not valid and cannot be coerced or adapted to a valid value.

  • validate ( self, object, name, value )

    This method validates, coerces, or adapts the specified value as the value of the name trait of the object object. This method is called when a value is assigned to an object trait that is based on this subclass of TraitType and the class does not contain a definition for either the get() or set() methods. This method must return the original value or any suitably coerced or adapted value that is a legal value for the trait. If value is not a legal value for the trait, and cannot be coerced or adapted to a legal value, the method should either raise a TraitError or call the error method to raise the TraitError on its behalf.

  • is_valid_for ( self, value )

    As an alternative to implementing the validate method, you can instead implement the is_valid_for method, which receives only the value being assigned. It should return True if the value is valid, and False otherwise.

  • value_for ( self, value )

    As another alternative to implementing the validate method, you can instead implement the value_for method, which receives only the value being assigned. It should return the validated form of value if it is valid, or raise a TraitError if the value is not valid.

  • post_setattr ( self, object, name, value )

    This method allows the trait to do additional processing after value has been successfully assigned to the name trait of the object object. For most traits there is no additional processing that needs to be done, and this method need not be defined. It is normally used for creating “shadow” (i.e., “mapped” traits), but other uses may arise as well. This method does not need to return a value, and should normally not raise any exceptions.

init()[source]

Allows the trait to perform any additional initialization needed.

get_default_value()[source]

Returns a tuple of the form: (default_value_type, default_value) which describes the default value for this trait. The default implementation analyzes the value of the trait’s default_value attribute and determines an appropriate default_value_type for default_value. If you need to override this method to provide a different result tuple, the following values are valid values for default_value_type:

  • 0, 1: The default_value item of the tuple is the default value.
  • 2: The object containing the trait is the default value.
  • 3: A new copy of the list specified by default_value is the default value.
  • 4: A new copy of the dictionary specified by default_value is the default value.
  • 5: A new instance of TraitListObject constructed using the default_value list is the default value.
  • 6: A new instance of TraitDictObject constructed using the default_value dictionary is the default value.
  • 7: default_value is a tuple of the form: (callable, args, kw), where callable is a callable, args is a tuple, and kw is either a dictionary or None. The default value is the result obtained by invoking callable(*args, **kw).
  • 8: default_value is a callable. The default value is the result obtained by invoking default_value*(*object), where object is the object containing the trait. If the trait has a validate() method, the validate() method is also called to validate the result.
  • 9: A new instance of TraitSetObject constructed using the default_value set is the default value.
clone(default_value=<missing>, **metadata)[source]

Clones the contents of this object into a new instance of the same class, and then modifies the cloned copy using the specified default_value and metadata. Returns the cloned object as the result.

Note that subclasses can change the signature of this method if needed, but should always call the ‘super’ method if possible.

get_value(object, name, trait=None)[source]

Returns the current value of a property-based trait.

set_value(object, name, value)[source]

Sets the cached value of a property-based trait and fires the appropriate trait change event.

as_ctrait()[source]

Returns a CTrait corresponding to the trait defined by this class.

class traits.trait_handlers.TraitHandler[source]

The task of this class and its subclasses is to verify the correctness of values assigned to object trait attributes.

This class is an alternative to trait validator functions. A trait handler has several advantages over a trait validator function, due to being an object:

  • Trait handlers have constructors and state. Therefore, you can use them to create parametrized types.
  • Trait handlers can have multiple methods, whereas validator functions can have only one callable interface. This feature allows more flexibility in their implementation, and allows them to handle a wider range of cases, such as interactions with other components.

The only method of TraitHandler that must be implemented by subclasses is validate().

validate(object, name, value)[source]

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

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

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

Description

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

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

class traits.trait_handlers.TraitRange(low=None, high=None, exclude_low=False, exclude_high=False)[source]

Ensures that a trait attribute lies within a specified numeric range.

TraitRange is the underlying handler for the predefined Range() trait factory.

Any value assigned to a trait containing a TraitRange handler must be of the correct type and in the numeric range defined by the TraitRange instance. No automatic coercion takes place. For example:

class Person(HasTraits):
    age = Trait(0, TraitRange(0, 150))
    weight = Trait(0.0, TraitRange(0.0, None))

This example defines a Person class, which has an age trait attribute, which must be an integer/long in the range from 0 to 150, and a weight trait attribute, which must be a non-negative float value.

class traits.trait_handlers.TraitString(minlen=0, maxlen=9223372036854775807, regex='')[source]

Ensures that a trait attribute value is a string that satisfied some additional, optional constraints.

The optional constraints include minimum and maximum lengths, and a regular expression that the string must match.

If the value assigned to the trait attribute is a Python numeric type, the TraitString handler first coerces the value to a string. Values of other non-string types result in a TraitError being raised. The handler then makes sure that the resulting string is within the specified length range and that it matches the regular expression.

Example

class Person(HasTraits):
    name = Trait('', TraitString(maxlen=50, regex=r'^[A-Za-z]*$'))

This example defines a Person class with a name attribute, which must be a string of between 0 and 50 characters that consist of only upper and lower case letters.

class traits.trait_handlers.TraitCoerceType(aType)[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
long int
unicode str
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')
class traits.trait_handlers.ThisClass(allow_none=False)[source]

Ensures that the trait attribute values belong to the same class (or a subclass) as the object containing the trait attribute.

ThisClass is the underlying handler for the predefined traits This and self, and the elements of ListThis.

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

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

TraitInstance is the underlying handler for the predefined trait Instance and the elements of List( Instance ).

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

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

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

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

class traits.trait_handlers.TraitWeakRef(aClass, allow_none=True, adapt='no', module='')[source]
class traits.trait_handlers.HandleWeakRef(object, name, value)[source]
class traits.trait_handlers.TraitClass(aClass)[source]

Ensures that trait attribute values are subclasses of a specified class (or the class itself).

A value is valid if it is a subclass of the specified class (including the class itself), or it is a string that is equivalent to the name of a valid class.

class traits.trait_handlers.TraitFunction(aFunc)[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.

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

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.

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.

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.

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

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

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

A cross between the TraitPrefixList and TraitMap classes.

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

Example

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

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

class traits.trait_handlers.TraitExpression[source]

Ensures that a value assigned to a trait attribute is a valid Python expression. The compiled form of a valid expression is stored as the mapped value of the trait.

class traits.trait_handlers.TraitCompound(*handlers)[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.

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

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

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

class traits.trait_handlers.TraitCallable[source]

Ensures that the value of a trait attribute is a callable Python object (usually a function or method).

class traits.trait_handlers.TraitListEvent(index=0, removed=None, added=None)[source]
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.

class traits.trait_handlers.TraitListObject(trait, object, name, value)[source]
class traits.trait_handlers.TraitSetEvent(removed=None, added=None)[source]
class traits.trait_handlers.TraitSetObject(trait, object, name, value)[source]
copy()[source]

Return a true set object with a copy of the data.

class traits.trait_handlers.TraitDictEvent(added=None, changed=None, removed=None)[source]
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).

class traits.trait_handlers.TraitDictObject(trait, object, name, value)[source]

Private Functions

traits.trait_handlers._arg_count(func)[source]

Returns the correct argument count for a specified function or method.

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