← Back to index
enums_definition.py
True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 0
FP: 0
FN: 0
Optional: 2 / 16
1
"""
2
Tests
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
7
from
enum
import
Enum
,
EnumType
8
from
typing
import
Literal
,
assert_type
9
10
# > Type checkers should support the class syntax
11
12
13
class
Color1
(
Enum
):
14
RED
=
1
15
GREEN
=
2
16
BLUE
=
3
17
18
19
assert_type
(
Color1
.
RED
,
Literal
[
Color1
.
RED
])
20
21
22
# > The function syntax (in its various forms) is optional
23
24
Color2
=
Enum
(
"Color2"
,
"RED"
,
"GREEN"
,
"BLUE"
)
# E?
[too-many-positional-arguments] Too many positional arguments to function `Enum`: expected 2, got 4
25
Color3
=
Enum
(
"Color3"
,
[
"RED"
,
"GREEN"
,
"BLUE"
])
# E?
26
Color4
=
Enum
(
"Color4"
,
(
"RED"
,
"GREEN"
,
"BLUE"
))
# E?
27
Color5
=
Enum
(
"Color5"
,
"RED, GREEN, BLUE"
)
# E?
28
Color6
=
Enum
(
"Color6"
,
"RED GREEN BLUE"
)
# E?
29
Color7
=
Enum
(
"Color7"
,
[(
"RED"
,
1
),
(
"GREEN"
,
2
),
(
"BLUE"
,
3
)])
# E?
30
Color8
=
Enum
(
"Color8"
,
((
"RED"
,
1
),
(
"GREEN"
,
2
),
(
"BLUE"
,
3
)))
# E?
31
Color9
=
Enum
(
"Color9"
,
{
"RED"
:
1
,
"GREEN"
:
2
,
"BLUE"
:
3
})
# E?
32
33
assert_type
(
Color2
.
RED
,
Literal
[
Color2
.
RED
])
# E?
[invalid-type-form] Type arguments for `Literal` must be `None`, a literal value (int, bool, str, or bytes), or an enum member
34
assert_type
(
Color3
.
RED
,
Literal
[
Color3
.
RED
])
# E?
35
assert_type
(
Color4
.
RED
,
Literal
[
Color4
.
RED
])
# E?
36
assert_type
(
Color5
.
RED
,
Literal
[
Color5
.
RED
])
# E?
37
assert_type
(
Color6
.
RED
,
Literal
[
Color6
.
RED
])
# E?
38
assert_type
(
Color7
.
RED
,
Literal
[
Color7
.
RED
])
# E?
39
assert_type
(
Color8
.
RED
,
Literal
[
Color8
.
RED
])
# E?
40
assert_type
(
Color9
.
RED
,
Literal
[
Color9
.
RED
])
# E?
41
42
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
46
47
48
class
CustomEnum1
(
Enum
):
49
pass
50
51
52
class
Color10
(
CustomEnum1
):
53
RED
=
1
54
GREEN
=
2
55
BLUE
=
3
56
57
58
assert_type
(
Color10
.
RED
,
Literal
[
Color10
.
RED
])
59
60
61
class
CustomEnumType
(
EnumType
):
62
pass
63
64
65
class
CustomEnum2
(
metaclass
=
CustomEnumType
):
66
pass
67
68
69
class
Color11
(
CustomEnum2
):
70
RED
=
1
71
GREEN
=
2
72
BLUE
=
3
73
74
75
assert_type
(
Color11
.
RED
,
Literal
[
Color11
.
RED
])