Named tuples
Mypy recognizes named tuples and can type check code that defines oruses them. In this example, we can detect code trying to access amissing attribute:
- Point = namedtuple('Point', ['x', 'y'])
- p = Point(x=1, y=2)
- print(p.z) # Error: Point has no attribute 'z'
If you use namedtuple
to define your named tuple, all the itemsare assumed to have Any
types. That is, mypy doesn’t know anythingabout item types. You can use NamedTuple
to also defineitem types:
- from typing import NamedTuple
- Point = NamedTuple('Point', [('x', int),
- ('y', int)])
- p = Point(x=1, y='x') # Argument has incompatible type "str"; expected "int"
Python 3.6 introduced an alternative, class-based syntax for named tuples with types:
- from typing import NamedTuple
- class Point(NamedTuple):
- x: int
- y: int
- p = Point(x=1, y='x') # Argument has incompatible type "str"; expected "int"