Typing¶
Python’s type hints provide you with optional static typing to leverage the best of both static and dynamic typing.
name: str = "bob"
name = 100 # error detected
def my_function(name: str) -> None:
print(f'hello {name}')
my_function(name)
my_function(1) # error detected
#Set type hints for multiple types
from typing import Union
def add (x: Union(int, float), y: Union[int, float]) -> Union[int, float]:
return x + y
# use an alias
number = Union[int, float]
def add(x: number, y: number) -> number:
return x + y
Type aliases from typing module:
Alias |
Built-in Type |
Alias |
Built-in Type |
---|---|---|---|
List |
list |
Frozenset |
frozenset |
Dict |
dict |
Sequence |
For list, tuple, and any other sequence type |
Set |
set |
Mapping |
For dict, set, frozenset, and any other mapping data type |
Tuple |
tuple |
ByteString |
bytes, bytearray, and memoryview types. |
from typing import List
ratings: List[int] = [1, 2, 3]
Mypy¶
A static type checker for Python and is designed with gradual typing in mind.
$ mypy program.py
$ mypy <python pkg>
$ mypy --disallow-untyped-defs <python pkg>
$ mypy --strict <python pkg>
Mypy requires type annotations for every imported module to pass without errors and stub files for commonly used modules are available from the typeshed project
$ python3 -m pip install types-requests