Search code examples
pythontraitsenthought

Typecast from Enthoughts traits to python native objects


This seems to be a trivial task, still I do not find a solution.

When using the API of enthought.traits and working with their data types (e.g. an integer Int), how can I typecast these values into native python objects within the HasTraits class. For example:

from traits.api import HasTraits, Int, List
class TraitsClass(HasTraits):
    test = Int(10)
    channel = List(range(0,test)) # this fails as range expects integers

I tried the following within the class, both yielding errors

test_int = int(test)
test_int = test.get_value()

Someone having a quick hint for me? Thanks a lot.


Solution

  • This is an answer to the revised question.

    Initializing the List trait at class declaration time fails because, at that stage, test is still a Trait instance. The value that you need is only created at the time the class is instantiated (see previous answer).

    Instead, you should use the default initializer for channel:

    In [22]: from traits.api import HasTraits, Int, List
    
    In [24]: class TraitsClass(HasTraits):
        test = Int(10)
        channel = List               
        def _channel_default(self):
            return range(0, self.test)
       ....:     
    
    In [25]: t=TraitsClass()
    
    In [26]: t.channel
    Out[26]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]