Why Use Traits?
Python does not require the data type of variables to be declared. As
any experienced Python programmer knows, this flexibility has both
good and bad points. The Traits package was developed to address
some of the problems caused by not having declared variable types, in
those cases where problems might arise. In particular, the motivation
for Traits came as a direct result of work done on Chaco, an open source scientific plotting package.
Chaco provides a set of high-level plotting objects, each of which has a number of user-settable attributes, such as line color, text font, relative location, and so on. To make the objects easy for scientists and engineers to use, the attributes attempt to accept a wide variety and style of values. For example, a color-related attribute of a Chaco object might accept any of the following as legal values for the color red:
- ( 1.0, 0.0, 0.0, 1.0 )
Thus, the user might write::
plotitem.color = 'red'
In a predecessor to Chaco, providing such flexibility came at a cost:
- When the value of an attribute was used by an object internally (for example, setting the correct pen color when drawing a plot line), the object would often have to map the user-supplied value to a suitable internal representation, a potentially expensive operation in some cases.
- If the user supplied a value outside the realm accepted by the object internally, it often caused disastrous or mysterious program behavior. This behavior was often difficult to track down because the cause and effect were usually widely separated in terms of the logic flow of the program.
So, one of the main goals of the Traits package is to provide a form of type checking that:
- Allows for flexibility in the set of values an attribute can have, such as allowing 'red', 0xFF0000 and ( 1.0, 0.0, 0.0, 1.0 ) as equivalent ways of expressing the color red.
- Catches illegal value assignments at the point of error, and provides a meaningful and useful explanation of the error and the set of allowable values.
- Eliminates the need for an object’s implementation to map user- supplied attribute values into a separate internal representation.
In the process of meeting these design goals, the Traits package evolved
into a useful component in its own right, satisfying all of the above
requirements and introducing several additional, powerful features of
its own. In projects where the Traits package has been used, it has
proven valuable for enhancing programmers’ ability to understand
code, during both concurrent development and maintenance.