Oct 19, 2019 by Thibault | 1050 views
Python is a dynamically typed language, meaning that the type of a variable can change during execution. This participates to the user friendliness of the language.
Strict types however can help spot bugs before execution (for a compiled language, you would say "at compilation"). Hence to help write beter code, Python 3 allows type hinting:
def func(a: int, b: int) -> int : return a + b c = func(1.234, 2) print(c)
However, type hints are not checked during execution. The code above, for example, will execute perfectly although 1.234 is obviously not an integer.
To check that your code uses methods correctly (or at least according to type hints), you should use mypy.
python3 -m pip install mypy
You can now run mypy against a single file, or against a directory:
$ mypy python-type-hinting.py python-type-hinting.py:6: error: Argument 1 to "func" has incompatible type "float"; expected "int" Found 1 error in 1 file (checked 1 source file)
Checking type hints should be part of your continuous integration chain. If you use GitLab to manage your code, simply add the following job to your .gitlab-ci.yml :
test:mypy: image: python:3.6 script: - pip install mypy --quiet - mypy src