Type hinting in Python, and testing with GitLab

Oct 19, 2019 by Thibault Debatty | 5563 views

Python GitLab


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)

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 :

    image: python:3.6
        - pip install mypy --quiet
        - mypy src

This blog post is licensed under CC BY-SA 4.0

This website uses cookies. More information about the use of cookies is available in the cookies policy.