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:

  1. Point = namedtuple('Point', ['x', 'y'])
  2. p = Point(x=1, y=2)
  3. 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:

  1. from typing import NamedTuple
  2.  
  3. Point = NamedTuple('Point', [('x', int),
  4. ('y', int)])
  5. 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:

  1. from typing import NamedTuple
  2.  
  3. class Point(NamedTuple):
  4. x: int
  5. y: int
  6.  
  7. p = Point(x=1, y='x') # Argument has incompatible type "str"; expected "int"