Type Hints in Python
In Typed Racket we are used to a very strong type discipline. We write the type or signature of every variable and function and DrRacket checks for us that the types match up.
Python has no such discipline. We don't even write down the types! So how can we keep track of them? Relatively recently (in version 3.5) Python introduced Type Hints, a way for us to write down and keep track of types.
Note that Python does not check the types. They are merely hints for us. There are indeed tools for checking the types, such as mypy, but they are beyond the scope of this course.
We can write type hintss for variables
a: int = 1 b: float = 1.0 c: bool = True d: str = "test"
For container types, such as List we import the type names from the typing
module.
from typing import List x: List[int] = [1]
We can take unions of types. For example if we have a list which can contain both strings and integers, we write
from typing import List, Union y: List[Union[int, str]] = [3, 5, "test", "fun"]
We can write signature hints for functions.
def bmi(weight: int, height: int) -> float: """Calculates Body Mass Index""" return weight / height ** 2
We can put unions to use for edge cases.
from typing import Union def get_batting_ave(hits: int, at_bats: int) -> Union[float, None]: if at_bats and at_bats > 0: return round(hits / at_bats, 3) else: return None
This can be written more directly as:
from typing import Optional def get_batting_ave(hits: int, at_bats: int) -> Optional[float]: if at_bats and at_bats > 0: return round(hits / at_bats, 3) else: return None
The most general type is Any. For example, a list which can contain elements
of any type can be written:
stuff: List[Any] = [123, "abc", True, 42.0]