Pre-commit python mypy checks all files not just committed files

781 Views Asked by At

I'm new to pre-commit, but I expect it to run hooks on only staged files. This is the case for the flake8 hook, but not the mypy hook in my .pre-commit-config.yaml file:

- repo: https://github.com/PyCQA/flake8
  rev: 6.1.0
  hooks:
    - id: flake8
      name: "lint python files - flake8"

- repo: https://github.com/pre-commit/mirrors-mypy
  rev: v1.7.0
  hooks:
    - id: mypy
      name: "check type hints"
      args: [--ignore-missing-imports,--disallow-untyped-defs]

Before running git commit, git status shows:

$ git status
On branch my-branch
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
    modified:   file1.py

and yet the mypy pre-commit hook prints:

check type hints.........................................................Failed
- hook id: mypy
- exit code: 1

file2.py:5: error: Function is missing a return type annotation  [no-untyped-def]
file3.py:40: error: Function is missing a type annotation for one or more arguments  [no-untyped-def]
Found 2 errors in 2 files (checked 1 source file)

I am likely misunderstanding something, but it seems strange that the mypy error log says that there are 2 errors in 2 files when only 1 source file was checked, especially since the two files in the mypy error log were not modified. Is there something about the additional arguments that I've passed which trigger a check on all files?

1

There are 1 best solutions below

0
On

You can tell mypy to not follow imports by adding a "--follow-imports=skip" flag to your mypy args. But in most cases you don't want to do that, as it really limits the type checker from finding and reporting issues.

For a starting point you could try using it, but the only real long term solution is to eventually add type hints to the whole package, starting with the most commonly imported files first.