Skip to content

Literal of enum values #781

@vnmabus

Description

@vnmabus

I am trying to implement a function that, as the type of one argument, can accept either an Enum or a value of such an enum (because some Python programmers are more used to type strings instead of enum values). Currently I have managed to do the following:

class LinkageCriterion(enum.Enum):
    WARD = "ward"
    COMPLETE = "complete"
    AVERAGE = "average"
    SINGLE = "single"


LinkageCriterionLike = Union[
    LinkageCriterion,
    Literal["ward", "complete", "average", "single"]
]

My question is if there is a way to not repeat myself here, that is, if you can construct a Literal from the values of a given Enum, and if so, how?

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: featureDiscussions about new features for Python's type annotations

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions