Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Enum class (with tostring fromstring)

I've found a simply way to implement(hack) an enum into Python:

class MyEnum:
  VAL1, VAL2, VAL3 = range(3)

I can then call this as such:

bob = MyEnum.VAL1

Sexy!

Alright, now I want to be able to get both the numerical value if given a string, or a string if given a numerical value. Let's say I want the strings to exactly match up to the Enum key's

The best I could think of is something like this:

class MyEnum:
  VAL1, VAL2, VAL3 = range(3)
  @classmethod
  def tostring(cls, val):
    if (val == cls.VAL1):
      return "VAL1"
    elif (val == cls.VAL2):
      return "VAL2"
    elif (val == cls.VAL3):
      return "VAL3"
    else:
      return None
  @classmethod
  def fromstring(cls, str):
    if (str.upper() == "VAL1"):
      return cls.VAL1
    elif (str.upper() == "VAL2"):
      return cls.VAL2
    elif (str.upper() == "VAL2"):
      return cls.VAL2
    else:
      return None

or something like that (ignore how i'm catching invalid cases)

Is there a better, more python centric way to do what I'm doing above? Or is the above already as concise as it gets.

It seems like there's got to be a better way to do it.

like image 261
Nick Avatar asked Dec 17 '10 17:12

Nick


People also ask

What happens if you ToString an enum?

ToString() Converts the value of this instance to its equivalent string representation.

Is enum Pythonic?

Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over. An enum has the following characteristics.

What is enum ToString?

toString() method returns the name of this enum constant, as contained in the declaration.


1 Answers

Well, here is what you asked for:

class MyEnum:
  VAL1, VAL2, VAL3 = range(3)
  @classmethod
  def tostring(cls, val):
    for k,v in vars(cls).iteritems():
        if v==val:
            return k

  @classmethod
  def fromstring(cls, str):
      return getattr(cls, str.upper(), None)

print MyEnum.fromstring('Val1')
print MyEnum.tostring(2)

But I really don't get the point of Enums in Python. It has such a rich type system as well as generators and coroutines to manage states.

I know I've not been using Enums in Python for more than 12 years, maybe you can get rid of them too ;-)

like image 147
Jochen Ritzel Avatar answered Nov 12 '22 14:11

Jochen Ritzel