Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traits Enum values

I'm having trouble setting an Enum value to one of it's possibility in a class...

If I have in an iPython window:

eTest = Enum('zero', 'one', 'two', 'three')

I can do:

eTest.value = eTest.values[2]

and print eTest.value gives me the correct answer: two

I'm trying the same thing in a python class, and it tells me that:

AttributeError: 'str' object has no attribute 'values'

how can I set eTest to have the [3] value of the Enums without having to type in the word 'three'?

like image 809
Steve76063 Avatar asked Feb 12 '23 10:02

Steve76063


1 Answers

You do not work with Enum objects like this. The Enum object is just a kind of declaration that tells the HasTraits class that has one of these to make an instance attribute that does a particular kind of validation. This instance attribute will not be an Enum object: it will be one of the enumerated values. The .value attribute that you were modifying on the Enum object just changes what the default value is going to be. It's not something you set during the lifetime of your object.

from traits.api import Enum, HasTraits, TraitError


ETEST_VALUES = ['zero', 'one', 'two', 'three']


class Foo(HasTraits):
    eTest = Enum(*ETEST_VALUES)


f = Foo()
assert f.eTest == 'zero'
f.eTest = 'one'
f.eTest = ETEST_VALUES[3]

try:
    f.eTest = 'four'
except TraitError:
    print 'Oops! Bad value!'

how can I set eTest to have the [3] value of the Enums without having to type in the word 'three'?

You can follow my example above and keep the list separate from the Enum() call and just index into it when you need to.

like image 61
Robert Kern Avatar answered Feb 15 '23 00:02

Robert Kern