Search code examples
pythonmypy

How to avoid mypy checking explicitly excluded but imported modules _without_ manually adding `type:ignore` (autogenerated)?


In the following MWE, I have two files/modules:

  1. main.py which is and should be checked with mypy
  2. and importedmodule.py which should not be type checked because it is autogenerated. This file is autogenerated, I don't want to add type:ignore.

MyPy Command

$ mypy main.py --exclude '.*importedmodule.*'
$ mypy --version
mypy 0.931

main.py

"""
This should be type checked
"""

from importedmodule import say_hello

greeting = say_hello("Joe")
print(greeting)

importedmodule.py

"""
This module should not be checked in mypy, because it is excluded
"""


def say_hello(name: str) -> str:
    # This function is imported and called from my type checked code
    return f"Hello {name}!"


def return_an_int() -> int:
    # ok, things are obviously wrong here but mypy should ignore them
    # also, I never expclitly imported this function
    return "this is a str, not an int" # <-- this is line 14 referenced in the mypy error message

But MyPy complains about the function that is not even imported in main.py:

importedmodule.py:14: error: Incompatible return value type (got "str", expected "int") Found 1 error in 1 file (checked 1 source file)

What is wrong about my exclude?


Solution

  • Here is SUTerliakov's comment on your question written as an answer.

    In the pyproject.toml file you can insert the following below your other mypy config

    [[tool.mypy.overrides]]
    module = "importedmodule"
    ignore_errors = true
    

    With this config you will ignore all errors coming from the mentioned module.

    By using a wildcard, you can also ignore all modules in a directory:

    [[tool.mypy.overrides]]
    module = "importedpackage.*"
    ignore_errors = true
    

    Related Documentation: