Created
July 18, 2023 22:03
-
-
Save PeterJCLaw/d4334e498ab1391ee306886748e675f1 to your computer and use it in GitHub Desktop.
Python enum value annotation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import enum | |
class PlainEnum(enum.Enum): | |
FIRST = 'first' | |
SECOND = 'second' | |
FAIL = 5 | |
reveal_type(PlainEnum.FIRST) # Revealed type is 'Literal[demo.PlainEnum.FIRST]?' | |
reveal_type(PlainEnum.FIRST.value) # Revealed type is 'builtins.str' # newer: Revealed type is "Literal['first']?" | |
p: PlainEnum | |
reveal_type(p) # Revealed type is 'demo.PlainEnum' | |
reveal_type(p.value) # Revealed type is 'Any' | |
class InheritEnum(str, enum.Enum): | |
FIRST = 'first' | |
SECOND = 'second' | |
FAIL = 5 | |
reveal_type(InheritEnum.FIRST) # Revealed type is 'Literal[demo.InheritEnum.FIRST]?' | |
reveal_type(InheritEnum.FIRST.value) # Revealed type is 'builtins.str' # newer: Revealed type is "Literal['first']?" | |
i: InheritEnum | |
reveal_type(i) # Revealed type is 'demo.InheritEnum' | |
reveal_type(i.value) # Revealed type is 'Any' | |
class AnnotatedPlainEnum(enum.Enum): | |
value: str | |
FIRST = 'first' | |
SECOND = 'second' | |
FAIL = 5 | |
reveal_type(AnnotatedPlainEnum.FIRST) # Revealed type is 'Literal[demo.AnnotatedPlainEnum.FIRST]?' | |
reveal_type(AnnotatedPlainEnum.FIRST.value) # Revealed type is 'builtins.str' | |
ap: AnnotatedPlainEnum | |
reveal_type(ap) # Revealed type is 'demo.AnnotatedPlainEnum' | |
reveal_type(ap.value) # Revealed type is 'builtins.str' | |
class AnnotatedInheritEnum(str, enum.Enum): | |
value: str | |
FIRST = 'first' | |
SECOND = 'second' | |
FAIL = 5 | |
reveal_type(AnnotatedInheritEnum.FIRST) # Revealed type is 'Literal[demo.AnnotatedInheritEnum.FIRST]?' | |
reveal_type(AnnotatedInheritEnum.FIRST.value) # Revealed type is 'builtins.str' | |
ai: AnnotatedInheritEnum | |
reveal_type(ai) # Revealed type is 'demo.AnnotatedInheritEnum' | |
reveal_type(ai.value) # Revealed type is 'builtins.str' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment