Search code examples
pythonmypy

Disallow untyped defs except in test directory


I would like to enforce type hints in the source code of a package, but not in the test code. Is there a way to use disallow_untyped_defs = true while excluding the tests directory?

Here is what I have tried:

pyproject.toml:

[tool.mypy]
disallow_untyped_defs = true
untyped_calls_exclude = ["tests"]

src/mymodule/file.py:

def hello_world() -> None:
    print("hi there!")

an empty src/mymodule/__init__.py, and tests/test_file.py:

def test_1():
    assert 1 < 2

But running mypy tests src/mymodule returns:

tests/test_file.py:1: error: Function is missing a return type annotation [no-untyped-def]
tests/test_file.py:1: note: Use "-> None" if function does not return a value
Found 1 error in 1 file (checked 3 source files)

I know I can limit the input directories by running mypy src/mymodule to limit the inputs, but I'd still like to lint the other type hinting warnings in the tests directory. I'd also like to silence the untyped-def errors raised by the VSCode Mypy Type Checker extension while developing.


Solution

  • You can configure mypy to silence some or all errors in any desired module. In pyproject.toml, the following will silence all mypy errors in tests folder (something I always do, since typing tests for non-library code is too pointless, but you may not want).

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

    The following will only allow untyped (fully or partially) declarations:

    [tool.mypy]
    disallow_untyped_defs = true
    
    [[tool.mypy.overrides]]
    disallow_incomplete_defs = false
    disallow_untyped_defs = false
    module = ["tests.*"]
    

    You can adjust most of other configuration flags on a per-module basis in the same way.