How to type-hint an Enum of strings in Python

Viewed 5993

I was curious how I'd type-hint an enumeration of strings, for example: ["keyword1", "keyword2"]

I'd want some variable, v, to be equal to any of these string literals. I could accomplish this with a union of literals - Union[Literal["keyword1"], Literal["keyword2"]] but it'd be make maintainability difficult if one of these keywords gets changed in the future. Ideally, I'd want to define things like this:

class Keywords(enum):
   keywordOne = "keyword1"
   keywordTwo = "keyword2"
v: valueOf[Keywords] = Keywords.keywordOne.value # v = "keyword1"

But I'm not sure how to accomplish something like this in MyPy

1 Answers

You're nearly there. It seems like what you're looking for is a custom enum object that is itself typed and then type annotations that dictate the use of that enum. Something like this:

from enum import Enum
from typing import Literal

class CustomKeyword(Enum):
   keywordOne: Literal["keyword1"] = "keyword1"
   keywordTwo: Literal["keyword2"] = "keyword2"

v: CustomKeyword = CustomKeyword.keywordOne

Does this not give you the expected outcome?

Related