What is the easiest / most pythonic way of create a Literal from an enum values?

Viewed 65

As the question suggests, imagine the following Enum:

class Suits(Enum):
    CLUBS = "CLUBS"
    DIAMONDS = "DIAMONDS"
    HEARTS = "HEARTS"
    SPADES = "SPADES"

I want to create a Literal from the Enum values. The only way I managed to do it:

Suit = Literal[Suits.CLUBS, Suits.DIAMONDS, Suits.HEARTS, Suits.SPADES]

Which is fine for small enums, but tiring and very error prone for bigger ones.

Hence my question, is there a better way of accomplishing the Literal creation?


EDIT

As pointed out by @chepner in the comments, we can (should?) use the Enum for type checking

1 Answers

I think the most clear and readable way to do it is the following:

enum_values_str = [suit.value for suit in Suits]

value directly gives you the value of an enum and in your case it is a string. Otherwise you could do str(suit.value) to convert it to a string.

Related