Redefinitions with incompatible types

Each name within a function only has a single ‘declared’ type. You canreuse for loop indices etc., but if you want to use a variable withmultiple types within a single function, you may need to declare itwith the Any type.

  1. def f() -> None:
  2. n = 1
  3. ...
  4. n = 'x' # Type error: n has type int

Note

This limitation could be lifted in a future mypyrelease.

Note that you can redefine a variable with a more precise or a moreconcrete type. For example, you can redefine a sequence (which doesnot support sort()) as a list and sort it in-place:

  1. def f(x: Sequence[int]) -> None:
  2. # Type of x is Sequence[int] here; we don't know the concrete type.
  3. x = list(x)
  4. # Type of x is List[int] here.
  5. x.sort() # Okay!