3.7. Basic Type Annotations

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

  • Since Python 3.5

  • SyntaxError in Python before 3.5

  • Sometimes called "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 in CI/CD Tools)

3.7.1. Rationale

  • Good IDE will highlight, incorrect types

def add_numbers(a: int, b: float) -> int:
    return int(a + b)


add_numbers(1, 2.5)
add_numbers('a', 'b')       # Good IDE should highlight the problem here

3.7.2. Annotating Basic Types

value: int = 30
value: int = -30
Listing 34. Type Annotations
value: float = 13.37
my_str: str = ''
my_str: str = 'Jan Twardowski'
my_var: bool = True
my_var: bool = False

3.7.3. 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

3.7.4. More Advanced Topics

Note

The topic will be continued in chapter: Type Annotation