5.4.1
Example Custom Trait Handler
The following example defines the OddInt trait (also
implemented as a trait type in Section 5.1.1) using a TraitHandler subclass.
# custom_traithandler.py --- Example of a custom TraitHandler
import types
from enthought.traits.api import TraitHandler
class
TraitOddInteger(TraitHandler):
def
validate(self, object, name, value):
if
((type(value) is types.IntType) and
(value > 0) and ((value % 2) == 1)):
return value
self.error(object, name, value)
def
info(self):
return 'a positive odd integer'
An application could use this new trait handler to define
traits such as the following:
#
use_custom_th.py --- Example of using a custom TraitHandler
from
enthought.traits.api import HasTraits, Trait, TraitRange
from
custom_traithandler import TraitOddInteger
class
AnOddClass(HasTraits):
oddball
= Trait(1, TraitOddInteger())
very_odd
= Trait(-1, TraitOddInteger(),
TraitRange(-10, -1))
The following example demonstrates why the info() method
returns a phrase rather than a complete sentence:
>>>
from use_custom_th import AnOddClass
>>>
odd_stuff = AnOddClass()
>>>
odd_stuff.very_odd = 0
Traceback
(most recent call last):
File
"test.py", line 25, in ?
odd_stuff.very_odd = 0
File
"C:\wrk\src\lib\enthought\traits\traits.py", line 1119, in validate
raise
TraitError, excp
traits.traits.TraitError:
The 'very_odd' trait of a AnOddClass instance must be a
positive odd integer or an integer in the range from -10 to -1, but a
value of 0 was specified.
Note the emphasized result returned by the info() method,
which is embedded in the exception generated by the invalid assignment.
|