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.
- def f() -> None:
- n = 1
- ...
- 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:
- def f(x: Sequence[int]) -> None:
- # Type of x is Sequence[int] here; we don't know the concrete type.
- x = list(x)
- # Type of x is List[int] here.
- x.sort() # Okay!