Explicit types for variables

You can override the inferred type of a variable by using avariable type annotation:

  1. from typing import Union
  2.  
  3. x: Union[int, str] = 1

Without the type annotation, the type of x would be just int. Weuse an annotation to give it a more general type Union[int, str] (thistype means that the value can be either an int or a str).Mypy checks that the type of the initializer is compatible with thedeclared type. The following example is not valid, since the initializer isa floating point number, and this is incompatible with the declaredtype:

  1. x: Union[int, str] = 1.1 # Error!

The variable annotation syntax is available starting from Python 3.6.In earlier Python versions, you can use a special comment after anassignment statement to declare the type of a variable:

  1. x = 1 # type: Union[int, str]

We’ll use both syntax variants in examples. The syntax variants aremostly interchangeable, but the variable annotation syntax allowsdefining the type of a variable without initialization, which is notpossible with the comment syntax:

  1. x: str # Declare type of 'x' without initialization

Note

The best way to think about this is that the type annotation sets thetype of the variable, not the type of the expression. To force thetype of an expression you can use cast(<type>, <expression>).