Python type annotation specificity


Python tip:

Specify the most general type for inputs and the most specific type for outputs.

For example:

from typing import List


def sum_of_elements(elements: List[int]) -> int:
    sum_el = 0

    for element in elements:
        sum_el += element

    return sum_el


print(sum_of_elements((9, 9)))

"""
$ mypy example.py

example.py:13: error: Argument 1 to "sum_of_elements" has 
incompatible type "Tuple[int, int]"; expected "List[int]"
Found 1 error in 1 file (checked 1 source file)
"""

from typing import Iterable


def sum_of_elements(elements: Iterable[int]) -> int:
    sum_el = 0

    for element in elements:
        sum_el += element

    return sum_el


print(sum_of_elements((9, 9)))

"""
$ mypy example.py

Success: no issues found in 1 source file
"""