API Reference for Enthought Tool Suite 3.0.1

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

Inherits from

Attributes

Inherited from base classes

Method summary

Inherited from base classes

Methods

© Copyright 2002-2008 Enthought, Inc.