koks der drache
koks der drache

Reputation: 1849

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?

Upvotes: 12

Views: 15035

Answers (2)

unlimitedfox
unlimitedfox

Reputation: 479

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:

Upvotes: 10

AlexLoss
AlexLoss

Reputation: 581

From the mypy documentation,

In particular, --exclude does not affect mypy’s import following. You can use a per-module follow_imports config option to additionally avoid mypy from following imports and checking code you do not wish to be checked.

Unfortunately it doesn't seem like there is a cli option for disabling mypy for unused functions in imported modules. When importing a module, mypy analyses all of it. The static analyser doesn't check if a function is used or not.

However you can silence any errors created in those imported modules

$ mypy main.py --follow-imports silent
Success: no issues found in 1 source file
$ mypy main.py --follow-imports skip
Success: no issues found in 1 source file

Upvotes: 5

Related Questions