Compatibility of container types

The following program generates a mypy error, since List[int]is not compatible with List[object]:

  1. def f(l: List[object], k: List[int]) -> None:
  2. 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:

  1. def f(l: List[object], k: List[int]) -> None:
  2. l = k
  3. l.append('x')
  4. 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.