2.7. Type Annotation

Types are not required, and never will be -- Guido van Rossum, Python BDFL

2.7.1. Rationale

  • Since Python 3.5

  • SyntaxError in Python before 3.5

  • Also known as "type hints"

  • Good IDE will give you hints

  • Types are used extensively in system libraries

  • More and more books and documentations use types

  • To type check use: mypy or pyre-check

  • More information in CI/CD Tools

2.7.2. Int

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

2.7.3. Float

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

2.7.4. Str

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

2.7.5. Bool

data: bool = True
data: bool = False

2.7.6. Optional

from typing import Optional


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

2.7.7. Final

New in version Python: 3.8 See PEP 591

from typing import Final


METER: Final = 1
KILOMETER: Final[int] = 1000 * METER

2.7.8. 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.7.9. More Information

Note

More information in Type Annotations and Type Checking