← 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"""
2Tests NamedTuple type compatibility rules.
3"""
4
5from typing import Any, NamedTuple
6
7# Specification: https://typing.readthedocs.io/en/latest/spec/namedtuples.html#type-compatibility-rules
8
9
10class Point(NamedTuple):
11 x: int
12 y: int
13 units: str = "meters"
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.
19p = Point(x=1, y=2, units="inches")
20v1: tuple[int, int, str] = p # OK
21v2: tuple[Any, ...] = p # OK
22v3: tuple[int, int] = p # E: too few elements
[invalid-assignment] Object of type `Point` is not assignable to `tuple[int, int]`
23v4: tuple[int, str, str] = p # E: incompatible element type
[invalid-assignment] Object of type `Point` is not assignable to `tuple[int, str, str]`
25# > As with normal tuples, named tuples are covariant in their type parameters.
27v5: tuple[float, float, str] = p # OK