Compatibility of container types
The following program generates a mypy error, since List[int]
is not compatible with List[object]
:
- def f(l: List[object], k: List[int]) -> None:
- l = k # Type check error: incompatible types in assignment
The reason why the above assignment is disallowed is that allowing theassignment could result in non-int values stored in a list of int
:
- def f(l: List[object], k: List[int]) -> None:
- l = k
- l.append('x')
- print(k[-1]) # Ouch; a string in List[int]
Other container types like Dict
and Set
behave similarly. Wewill discuss how you can work around this in Invariance vs covariance.
You can still run the above program; it prints x
. This illustratesthe fact that static types are used during type checking, but they donot affect the runtime behavior of programs. You can run programs withtype check failures, which is often very handy when performing a largerefactoring. Thus you can always ‘work around’ the type system, and itdoesn’t really limit what you can do in your program.