1

Let's say I have the enum:

class Example(Enum):
    a = "example1"
    b = "example2"
val = "a"
# print(Example.val.value) (?)

How can I get an enum value from a string using val? In my actual code, I need to do something like this because the name is unknown, and I need to access it from a string assigned to a variable.

e7Ceahje
  • 29
  • 1

3 Answers3

0

Try using square brackets:

from enum import Enum


class Example(Enum):
    a = "example1"
    b = "example2"


def main() -> None:
    val = "a"
    print(f"{val = }")
    print(f"{Example[val] = }")
    print(f"{Example[val].value = }")


if __name__ == "__main__":
    main()

Output:

val = 'a'
Example[val] = <Example.a: 'example1'>
Example[val].value = 'example1'
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
-1

You can make a string of the statement you want to execute, with the value of 'val' in it. Then evaluate the string using eval

from enum import Enum
class Example(Enum):
    a = "example1"
    b = "example2"
val = "a"
st = f"Example.{val}.value"
print(eval(st))

other way to make the string:

st = "Example."+val+"value"

or using Square Brackets:

print(Example[val].value)