4

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'?

Hooked
  • 84,485
  • 43
  • 192
  • 261
Steve76063
  • 317
  • 2
  • 10

1 Answers1

8

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.

Robert Kern
  • 13,118
  • 3
  • 35
  • 32
  • Excellent :) One of these days I'll get the hang of Python and Traits :). Your method works perfectly for me. – Steve76063 Jul 23 '14 at 22:03