2.1. Annotation Type

Types are not required, and never will be -- Guido van Rossum, Python initiator, core developer, former BDFL

2.1.1. Rationale

2.1.2. Int

data: int = 0
data: int = 1
data: int = -1

2.1.3. Float

data: float = 0.0
data: float = 1.23
data: float = -1.23

2.1.4. Str

data: str = ''
data: str = 'Jan Twardowski'

2.1.5. Bool

data: bool = True
data: bool = False

2.1.6. Optional

from typing import Optional

data: Optional[int] = 1
data: Optional[int] = None
from typing import Optional


firstname: str = 'Melissa'
lastname: str = 'Lewis'
age: Optional[float] = None

2.1.7. Union

from typing import Optional

data: Union[int, float] = 1
data: Union[int, float] = 1.1

2.1.8. Final

New in version Python: 3.8 See PEP 591

from typing import Final


m: Final[int] = 1
km: Final[int] = 1000 * m
from typing import Final

second: Final[int] = 1
minute: Final[int] = 60 * second
hour: Final[int] = 60 * hour
day: Final[int] = 24 * day

2.1.9. Type Check is not Enforced

  • This code will run without any problems

  • Although mypy or pyre-check will throw error

name: int = 'Jan Twardowski'
age: float = 30
is_adult: int = True

2.1.10. Future

New in version Python: 3.10 PEP 604 - Allow writing union types as X | Y

Listing 2.93. Union and Optional before Python 3.10
from typing import Union, Optional

age: Union[int, float] = 1337
age: Optional[int] = 1337
age: int|float = 1337
age: int|None = 1337
Listing 2.94. Result of this expression would then be valid in isinstance() and issubclass()
isinstance(1337, int|None)
isinstance(1337, int|float)
issubclass(bool, int|float)

2.1.11. More Information

Note

More information in Type Annotations and Type Checking