Variables vs type aliases

Mypy has both type aliases and variables with types like Type[…] and it is important to know their difference.

  • Variables with type Type[…] should be created by assignments with an explicit type annotations:
  1. class A: ...
  2. tp: Type[A] = A
  • Aliases are created by assignments without an explicit type:
  1. class A: ...
  2. Alias = A
  • The difference is that aliases are completely known statically and can be used in type context (annotations):
  1. class A: ...
  2. class B: ...
  3.  
  4. if random() > 0.5:
  5. Alias = A
  6. else:
  7. Alias = B # error: Cannot assign multiple types to name "Alias" without an explicit "Type[...]" annotation \
  8. # error: Incompatible types in assignment (expression has type "Type[B]", variable has type "Type[A]")
  9.  
  10. tp: Type[object] # tp is a type variable
  11. if random() > 0.5:
  12. tp = A
  13. else:
  14. tp = B # This is OK
  15.  
  16. def fun1(x: Alias) -> None: ... # This is OK
  17. def fun2(x: tp) -> None: ... # error: Variable "__main__.tp" is not valid as a type