← Back to index

enums_behaviors.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 3
FP: 0
FN: 0
Optional: 0 / 0
1"""
2Tests basic behaviors of of Enum classes.
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/enums.html#enum-definition
6
7from enum import Enum
8from typing import assert_type, Literal
9
10# > Enum classes are iterable and indexable, and they can be called with a
11# > value to look up the enum member with that value. Type checkers should
12# > support these behaviors
14class Color(Enum):
15 RED = 1
16 GREEN = 2
17 BLUE = 3
19for color in Color:
20 assert_type(color, Color)
22# > Unlike most Python classes, Calling an enum class does not invoke its
23# > constructor. Instead, the call performs a value-based lookup of an
24# > enum member.
26# 'Literal[Color.RED]' and 'Color' are both acceptable
27assert_type(Color["RED"], Color) # E[red]
28assert_type(Color["RED"], Literal[Color.RED]) # E[red]
Tag 'red' [type-assertion-failure] Type `Literal[Color.RED]` does not match asserted type `Color`
30# 'Literal[Color.BLUE]' and 'Color' are both acceptable
31assert_type(Color(3), Color) # E[blue]
32assert_type(Color(3), Literal[Color.BLUE]) # E[blue]
Tag 'blue' [type-assertion-failure] Type `Literal[Color.BLUE]` does not match asserted type `Color`
35# > An Enum class with one or more defined members cannot be subclassed.
37class EnumWithNoMembers(Enum):
38 pass
40class Shape(EnumWithNoMembers): # OK (because no members are defined)
41 SQUARE = 1
42 CIRCLE = 2
44class ExtendedShape(Shape): # E: Shape is implicitly final
[subclass-of-final-class] Class `ExtendedShape` cannot inherit from final class `Shape`
45 TRIANGLE = 3