Check that function return types match the def statements in PR test in python

Question:

I have a Github Action that runs unit tests on each Pull Request (PR).

It effectively runs pytest.

Seeing that we leverage the type hints introduced in PEP 484, I’d like a method like this to cause a PR check fail:

def return_an_int() -> int:
  return 'not an int'

Is there a simple way to run such a "compilation" test (I know python is interpreted) for all the .py files in the project?

Asked By: Joey Baruch

||

Answers:

This is the kind of type checking that mypy does, so you could include running mypy in your Action workflow.

If your module and its dependencies are already installed in your workflow, this step should do the trick:

      - name: Run mypy
        run: |
          # needed if mypy isn't already installed
          pip install mypy
          # "mypy somedir" looks for and checks all Python files under somedir
          # I assume your code is in some source directory <src-dir>
          mypy <src-dir>

And that should be all you need, placed after the steps that install your code base.

Answered By: someone