← Back to index
namedtuples_type_compat.py
True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 2
FP: 0
FN: 0
Optional: 0 / 0
1
"""
2
Tests
NamedTuple
type
compatibility
rules
.
3
"""
4
5
from
typing
import
Any
,
NamedTuple
6
7
# Specification: https://typing.readthedocs.io/en/latest/spec/namedtuples.html#type-compatibility-rules
8
9
10
class
Point
(
NamedTuple
):
11
x
:
int
12
y
:
int
13
units
:
str
=
"meters"
14
15
16
# > A named tuple is a subtype of a ``tuple`` with a known length and parameterized
17
# > by types corresponding to the named tuple's individual field types.
18
19
p
=
Point
(
x
=
1
,
y
=
2
,
units
=
"inches"
)
20
v1
:
tuple
[
int
,
int
,
str
]
=
p
# OK
21
v2
:
tuple
[
Any
,
...
]
=
p
# OK
22
v3
:
tuple
[
int
,
int
]
=
p
# E: too few elements
[invalid-assignment] Object of type `Point` is not assignable to `tuple[int, int]`
23
v4
:
tuple
[
int
,
str
,
str
]
=
p
# E: incompatible element type
[invalid-assignment] Object of type `Point` is not assignable to `tuple[int, str, str]`
24
25
# > As with normal tuples, named tuples are covariant in their type parameters.
26
27
v5
:
tuple
[
float
,
float
,
str
]
=
p
# OK