Chilichiller
Chilichiller

Reputation: 487

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.

Upvotes: 2

Views: 130

Answers (2)

pberkes
pberkes

Reputation: 5360

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]

Upvotes: 2

pberkes
pberkes

Reputation: 5360

You can access the default value you gave to the trait by test.default_value. However, I suspect that is not what you want to do...

In a normal use pattern, a trait needs to be used in a HasTraits class. When the class is instantiated, traits are transformed in regular Python object, with some machinery to listen to changes to the trait, etc.

For example:

In [14]: from traits.api import HasTraits, Int

In [15]: class Test(HasTraits):
   ....:     x = Int(10)
   ....:     

In [16]: test = Test()

In [17]: test.x
Out[17]: 10

In [18]: type(test.x)
Out[18]: int

Upvotes: 2

Related Questions