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.