← Back to index

enums_definition.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 0
FP: 0
FN: 0
Optional: 0 / 16
1"""
2Tests handling of Enum class definitions using the class syntax.
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/enums.html#enum-definition
6
7from enum import Enum, EnumType
8from typing import Literal, assert_type
9
10# > Type checkers should support the class syntax
13class Color1(Enum):
14 RED = 1
15 GREEN = 2
16 BLUE = 3
19assert_type(Color1.RED, Literal[Color1.RED])
22# > The function syntax (in its various forms) is optional
24Color2 = Enum("Color2", "RED", "GREEN", "BLUE") # E?
25Color3 = Enum("Color3", ["RED", "GREEN", "BLUE"]) # E?
26Color4 = Enum("Color4", ("RED", "GREEN", "BLUE")) # E?
27Color5 = Enum("Color5", "RED, GREEN, BLUE") # E?
28Color6 = Enum("Color6", "RED GREEN BLUE") # E?
29Color7 = Enum("Color7", [("RED", 1), ("GREEN", 2), ("BLUE", 3)]) # E?
30Color8 = Enum("Color8", (("RED", 1), ("GREEN", 2), ("BLUE", 3))) # E?
31Color9 = Enum("Color9", {"RED": 1, "GREEN": 2, "BLUE": 3}) # E?
33assert_type(Color2.RED, Literal[Color2.RED]) # E?
34assert_type(Color3.RED, Literal[Color3.RED]) # E?
35assert_type(Color4.RED, Literal[Color4.RED]) # E?
36assert_type(Color5.RED, Literal[Color5.RED]) # E?
37assert_type(Color6.RED, Literal[Color6.RED]) # E?
38assert_type(Color7.RED, Literal[Color7.RED]) # E?
39assert_type(Color8.RED, Literal[Color8.RED]) # E?
40assert_type(Color9.RED, Literal[Color9.RED]) # E?
43# > Enum classes can also be defined using a subclass of enum.Enum or any class
44# > that uses enum.EnumType (or a subclass thereof) as a metaclass.
45# > Type checkers should treat such classes as enums
48class CustomEnum1(Enum):
49 pass
52class Color10(CustomEnum1):
53 RED = 1
54 GREEN = 2
55 BLUE = 3
58assert_type(Color10.RED, Literal[Color10.RED])
61class CustomEnumType(EnumType):
62 pass
65class CustomEnum2(metaclass=CustomEnumType):
66 pass
69class Color11(CustomEnum2):
70 RED = 1
71 GREEN = 2
72 BLUE = 3
75assert_type(Color11.RED, Literal[Color11.RED])