Python Type Checking

Python is a dynamically typed language which makes it easy and fun to program. But sometimes -especially in bigger projects- it can become quite cumbersome when you just receive errors at run time.

Given the hypothetical example where we define a function which multiplies integer:

def multiply(a, b):
    return a * b

print(multiply("I", "You"))

It is possible to pass strings to the function which will produce am error at runtime

TypeError: can't multiply sequence by non-int of type 'str'

Type Hints

Since Python 3.5 you have the possibility to add type hints so that type checks can be performed _before_ run time:

def multiply(a: int, b: int) -> int:
    return a * b

You can also have type hints with default parameter values. They just look a bit weird 🙂

def __init__(self, wp_url: str, posts_per_page: int=20):
    self.wp_api_url = wp_url + "/wp-json/wp/v2"
    self.posts_per_page = posts_per_page

You can import more types from the typing module e.g. List

from typing import List
def get_categories(self) -> List:
    query_string = "/categories?per_page=20"
    categories = requests.get(self.wp_api_url + query_string)
    return categories.json()


If a function returns different object types we can use the union type

from typing import Union, Optional
def get_foo_or_bar(id: int) -> Union[Foo, Bar]

def get_foo_or_none(id: int) -> Union[Foo, None]
def get_foo_or_none(id: int) -> Optional[Foo]

Type Checking

With mypy there is tool to lint your python code before execution:

$ python3 pip install mypy

$ mypy <my_python_file>

IDE support

An IDE like PyCharm is already capable of checking types with type hints

A good tutorial on medium