I'm learning how to use Enum classes in Python, and have found that whenever I need to access the actual value of the enum, I need to append the .value property:
from enum import Enum
class Pets(Enum):
DOG = "Fido"
CAT = "Kitty"
Pets.DOG # yields Pets.DOG
Pets.DOG.value # yields Fido
As an exercise, I'm trying configure my Enum class so that I do not need to continually access that value property. My desired behavior is that when I call Pets.DOG, I get Fido as my value.
I'm tried to implement this with __getattr_(cls, item):
class Pets(Enum):
def __getattr__(self, item):
print(f"__getattr__ called with {item}")
return getattr(self, item).value
DOG = "Fido"
CAT = "Kitty"
if __name__ == "__main__":
pets = Pets()
pets.DOG
However, I receive a RecursionError: maximum recursion depth exceeded while calling a Python object, and item is a string value of _value_. I'm not quite understanding why this behavior is happening - is this built in Python behavior, or because I am using a special class Enum?
I did take a look at a similar SO post, but the solutions there were to use another module (inspect), or access the __dict__ or dir() and parse it yourself with a combination of conditionals or regex. Is there a better way to access the underlying Enum's value?