5from typing import NamedTuple, assert_type
7# Specification: https://typing.readthedocs.io/en/latest/spec/namedtuples.html#named-tuple-usage
10class Point(NamedTuple):
16# > The fields within a named tuple instance can be accessed by name using an
17# > attribute access (``.``) operator. Type checkers should support this.
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.
30assert_type(p[-1], str)
31assert_type(p[-2], int)
32assert_type(p[-3], int)
[index-out-of-bounds] Index 3 is out of bounds for tuple `Point` with length 3
[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
[invalid-assignment] Cannot assign to read-only property `x` on object of type `Point`
[invalid-assignment] Cannot assign to a subscript on an object of type `Point`
Expected a ty diagnostic for this line
[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
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):
60pn = PointWithName(1, 1)