9.2. Function Type Annotation

9.2.1. Type annotations

  • Since Python 3.5

  • Types are not forced

  • Twoje IDE porówna typy oraz poinformuje cię jeżeli wykryje niezgodność

  • Użyj mypy lub pyre-check do sprawdzania typów

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

add_numbers(1, 2)
# 3
Listing 83. Python will execute without even warning. Your IDE and mypy will yield errors.
def add_numbers(a: int, b: int) -> int:
    return a + b

add_numbers('Jan', 'Twardowski')
# 'JanTwardowski'
from typing import Union


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

add_numbers(1, 2)
# 3

add_numbers(1.5, 2.5)
# 4

Note

More about this topic at Type Annotation