← Back to index

namedtuples_usage.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 7
FP: 0
FN: 1
Optional: 0 / 0
1"""
2Tests NamedTuple usage.
3"""
4
5from typing import NamedTuple, assert_type
6
7# Specification: https://typing.readthedocs.io/en/latest/spec/namedtuples.html#named-tuple-usage
8
9
10class Point(NamedTuple):
11 x: int
12 y: int
13 units: str = "meters"
16# > The fields within a named tuple instance can be accessed by name using an
17# > attribute access (``.``) operator. Type checkers should support this.
19p = Point(1, 2)
20assert_type(p.x, int)
21assert_type(p.units, str)
24# > Like normal tuples, elements of a named tuple can also be accessed by index,
25# > and type checkers should support this.
27assert_type(p[0], int)
28assert_type(p[1], int)
29assert_type(p[2], str)
30assert_type(p[-1], str)
31assert_type(p[-2], int)
32assert_type(p[-3], int)
34print(p[3]) # E
[index-out-of-bounds] Index 3 is out of bounds for tuple `Point` with length 3
35print(p[-4]) # E
[index-out-of-bounds] Index -4 is out of bounds for tuple `Point` with length 3
37# > Type checkers should enforce that named tuple fields cannot be overwritten
38# > or deleted.
40p.x = 3 # E
[invalid-assignment] Cannot assign to read-only property `x` on object of type `Point`
41p[0] = 3 # E
[invalid-assignment] Cannot assign to a subscript on an object of type `Point`
42del p.x # E
Expected a ty diagnostic for this line
43del p[0] # E
[not-subscriptable] Cannot delete subscript on object of type `Point` with no `__delitem__` method
45# > Like regular tuples, named tuples can be unpacked. Type checkers should understand
46# > this.
48x1, y1, units1 = p
49assert_type(x1, int)
50assert_type(units1, str)
52x2, y2 = p # E: too few values to unpack
[invalid-assignment] Too many values to unpack: Expected 2
53x3, y3, unit3, other = p # E: too many values to unpack
[invalid-assignment] Not enough values to unpack: Expected 4
56class PointWithName(Point):
57 name: str = "" # OK
60pn = PointWithName(1, 1)
61x4, y4, units4 = pn