Search code examples
traitsenthought

How to change Enum possible values


The following code does not work:

from traits.api import HasTraits,  Enum

class A(HasTraits):

    enum = Enum(1,2,3)

class B(A):

    def __init__(self):
        self.trait('enum').default_value = ['one','two','three']

b = B()
b.configure_traits()

Instead of having the choice ['one','two','three'] in the drop-down list, it is still [1,2,3]. Is there a way to modify an Enum content in any way after it has been declared once?


Solution

  • If you want to change the value of the enum trait when you subclass B from A, you can just redefine the trait like so:

    class B(A):
        enum = Enum(['one', 'two', 'three'])
    

    If you want to be able to change the values in the Enum dynamically, the Enum constructor takes a values argument that you can pass the name of another trait that holds a sequence like a List trait that defines the values, like below, and then change the values in that list or the sequence in its entirety in any way you desire:

    from traits.api import Enum, HasTraits, List
    
    
    class A(HasTraits):
        values = List([1, 2, 3])
        enum = Enum(values='values')
    
    
    a = A()
    a.configure_traits()