I'm having trouble trying to dynamically initialize a Traits Range object.
The following code is a very simple example of what I'm trying to do, but sadly fails with the following type error:
TypeError: unsupported operand type(s) for -: 'int' and 'code'
from traits.api import HasTraits, Int, Range
from traitsui.api import View, Item
class DynamicRange(HasTraits):
"""Dynamic initialisation of a Range object"""
N = Int()
R = Range(low=0, high='N')
traits_view = View(Item('R'), Item('N'))
def __init__(self, N):
self.N = N # initial parameter value for N
def _N_default(self):
return self.N
Robject = DynamicRange(N=10)
Robject.configure_traits()
The code works if I replace the definition of 'R' with: R = Range(low=0, high=10), but then of course I don't get the dynamic initialization of the Range's high parameter that I'm seeking.
All suggestions gratefully accepted.
* Edit after Jonathan's response *
Here's the simple solution to my question using Jonathan's helpful suggestion below:
from traits.api import HasTraits, Range
from traitsui.api import View, Item
class DynamicRange(HasTraits):
"""Dynamic initialisation of a Range object"""
traits_view = View(Item('R'))
def __init__(self, N):
self.add_trait("R", Range(0, N))
Robject = DynamicRange(N=30)
Robject.configure_traits()
One method would be to define the trait not in the usual way, but within __init__
, thus:
self.add_trait("R", Range(0, N))
See http://docs.enthought.com/traits/traits_user_manual/advanced.html#per-object-trait-attributes