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

Inherits from

Attributes

Inherited from base classes

Method summary

Inherited from base classes

Methods

© Copyright 2002-2008 Enthought, Inc.