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.
ToString() Converts the value of this instance to its equivalent string representation.
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.
toString() method returns the name of this enum constant, as contained in the declaration.
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 ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With