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.

1

2 Answers 2

0

You could do something like Example[val].value.

https://docs.python.org/3/library/enum.html#programmatic-access-to-enumeration-members-and-their-attributes

Convert string to Enum in Python

Sign up to request clarification or add additional context in comments.

Comments

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'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.