Search code examples
pythonmypy

mypy exclude option is not working - bug?


MRE:

  • Make a folder (let's call it MyProjectFolder).
  • Make a helloroot.py empty file.
  • Make a subfolder named FolderNotIgnored.
  • Make a hello.py in that subfolder.
  • Make a mypy.ini file containing:
[mypy]
exclude=FolderNotIgnored/

The tree will look like this:

│   helloroot.py
│   mypy.ini
└───FolderNotIgnored
        hello.py

Open the terminal. Run pytest --mypy.

We expect mypy to ignore FolderNotIgnored\hello.py.

However, I get this:

================================================================= test session starts ==================================================================
platform win32 -- Python 3.12.5, pytest-8.3.4, pluggy-1.5.0
rootdir: C:\Users\CENSORED\Documents\Challenges\MyProjectFolder
plugins: anyio-4.8.0, hydra-core-1.3.2, mypy-0.10.3
collected 3 items                                                                                                                                        

FolderNotIgnored\hello.py ..                                                                                                                      [ 66%]
helloroot.py .                                                                                                                                    [100%] 
========================================================================= mypy ========================================================================= 

Success: no issues found in 2 source files
================================================================== 3 passed in 0.10s =================================================================== 

Solution

  • You need to stop pytest from collecting the file. Once it has been discovered by pytest it will always be passed explicitly to mypy. Mypy's docs state that exclude options are overridden if a file is passed explicitly.

    From the command line this looks like:

    pytest --ignore FolderNotIgnored --mpy
    

    From a config (using pyproject.toml), this would look like:

    [tool.pytest.ini_options]
    norecursedirs = ["FolderNotIgnored"]  # NB. No trailing /