pythonenthoughttraits

Instantiating a default instance for an Enthought trait


Consider this simple minimal example:

from traits.api import Instance, Str, HasTraits

class Person(HasTraits):
    name = Str("hooked")

class Chair(HasTraits):
    sitting = Instance(Person)

t = Chair()
print t.sitting.name

This fails since t.sitting evaluates to None. Enthought's traits module will enforce that the type of t.sitting is a Person but how can I get the default person to instantiate here? I don't want to pass any parameters to the Chair(**kwargs) I'd like this to be done automatically. The expected output to the print statement is hooked.


Solution

  • This is interesting. According to the Instance docstring, calling Instance will return None if klass is a class and arg and kw are not specified. arg and kw have default values of None and so calling Instance(Person) is returning None like you are seeing. I got your code to work by adding "kw = {}" or "args = []" to the Instance call.

    from traits.api import Instance, Str, HasTraits
    
    class Person(HasTraits):
        name = Str("hooked")
    
    class Chair(HasTraits):
        sitting = Instance(Person, kw = {})
    
    t = Chair()
    print t.sitting.name
    

    This prints "hooked" as expected.