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 quitre 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 a

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *