Emum not assigning values

Viewed 28

I have an enum class and I declare it as such for a state machine and declare a class as such

#file name is statefm.py
class State(Enum):
    START = auto
    MID = auto
    END = auto

class gate:

    def __init__(self):
        self.st = State.START
        self.counter = 0
        self.done = False
    def test(self):
        print(self.st)
        self.st = State.MID
        print(self.st)
        self.state = State.END
        print(self.st)

Then in another file, I do the necessary import, instantiate an object of the class and call the test class method,

import statefm

k = statefm.gate()
k.test()

Oddly, this is the output I get.

State.START
State.START
State.START

I also call list and all I get from list is just the first enum element in two places. Can I please get any help on this?

Thank you!

1 Answers

You are supposed to call it like auto(), not auto

from enum import Enum, auto

class State(Enum):
    START = auto()
    MID = auto()
    END = auto()

That using the bare name auto works at all is kind of a funny accident. All values just get aliased to the same class auto itself, and your resulting enumeration type actually only has one member, State.START, with two more aliases pointing to the same member.

>>> State.__members__
mappingproxy({'START': <State.START: <class 'enum.auto'>>,
              'MID': <State.START: <class 'enum.auto'>>,
              'END': <State.START: <class 'enum.auto'>>})
>>> len(State)
1
Related