2Tests that the type checker handles the `_value_` and `value` attributes correctly.
5# Specification: https://typing.readthedocs.io/en/latest/spec/enums.html#member-values
7# > All enum member objects have an attribute _value_ that contains the
8# > member’s value. They also have a property value that returns the same value.
9# > Type checkers may infer the type of a member’s value.
11from enum import Enum, auto
12from typing import Literal, assert_type
21assert_type(Color.RED._value_, Literal[1]) # E?
22assert_type(Color.RED.value, Literal[1]) # E?
25def func1(red_or_blue: Literal[Color.RED, Color.BLUE]):
26 assert_type(red_or_blue.value, Literal[1, 3]) # E?
29def func2(any_color: Color):
30 assert_type(any_color.value, Literal[1, 2, 3]) # E?
[type-assertion-failure] Type `Literal[1, 2, 3]` does not match asserted type `Any`
33# > The value of _value_ can be assigned in a constructor method. This
34# > technique is sometimes used to initialize both the member value and
35# > non-member attributes. If the value assigned in the class body is a tuple,
36# > the unpacked tuple value is passed to the constructor. Type checkers may
37# > validate consistency between assigned tuple values and the constructor
42 def __init__(self, value: int, mass: float, radius: float):
47 MERCURY = (1, 3.303e23, 2.4397e6)
48 VENUS = (2, 4.869e24, 6.0518e6)
49 EARTH = (3, 5.976e24, 6.37814e6)
50 MARS = (6.421e23, 3.3972e6) # E?: Type checker error (optional)
51 JUPITER = 5 # E?: Type checker error (optional)
54assert_type(Planet.MERCURY.value, Literal[1]) # E?
[type-assertion-failure] Type `Literal[1]` does not match asserted type `tuple[Literal[1], float, float]`
57# > The class enum.auto and method _generate_next_value_ can be used within
58# > an enum class to automatically generate values for enum members.
59# > Type checkers may support these to infer literal types for member values.
68assert_type(Color2.RED.value, Literal[1]) # E?
70# > If an enum class provides an explicit type annotation for _value_, type
71# > checkers should enforce this declared type when values are assigned to
Expected a ty diagnostic for this line
84 def __init__(self, value: int, mass: float, radius: float):
85 self._value_ = value # E
[invalid-assignment] Object of type `int` is not assignable to attribute `_value_` of type `str`
87 MERCURY = (1, 3.303e23, 2.4397e6)
90from _enums_member_values import ColumnType
92# > If the literal values for enum members are not supplied, as they sometimes
93# > are not within a type stub file, a type checker can use the type of the
96assert_type(ColumnType.DORIC.value, int) # E?
[type-assertion-failure] Type `int` does not match asserted type `Unknown`