pythonmypypython-typingpre-commit-hook

Python: enforce type hinting


I am wondering if there is a way to enforce type hints inside the Python projects?

Currently, I am using mypy pre-commit hook inside .pre-commit-config.yaml:

- repo: https://github.com/pre-commit/mirrors-mypy
  rev: v0.931
  hooks:
    - id: mypy

Using this hook, I will (correctly) not be able to commit the following piece of code due to type error when calling add function:

def add(a: int, b: int) -> int:
    return a + b

add(a=1.0, b=2.0)

However, using above combination of mypy and pre-commit hooks, type hints are still not fully enforced and I will be able to commit the following piece of code where no type hints are used:

def add(a, b):
    return a + b

I would also be curios, if enforcing type hints in a dynamically typed language such as Python is even a good idea in the first place? I know that I could opt instead for some statically typed language (e.g. Java) for my project, however, the reason I want to use Python with enforced type hints is because this allows me to rely on existing Python libraries (e.g. Tensorflow) while ensuring that the code written is of better quality because of specified types in function signatures.


Solution

  • Mypy exposes a bunch of option that you can set to enforce stricter or looser type checking, see for example mypy configuration documentation. For your case it would probably be disallow_untyped_defs, disallow_incomplete_defs, disallow_untyped_calls

    You have several options to set them, for example using a mypy.ini file, or if you want to keep everything in your pre-commit.yaml, you can add several command line arguments. For your exact case, that would look like

    - repo: https://github.com/pre-commit/mirrors-mypy
      rev: v0.931
      hooks:
        - id: mypy
          args: [--disallow-untyped-defs, --disallow-incomplete-defs, --disallow-untyped-calls]