Pytorch type annotations are buggy: how to suppress mypy errors

Hi,
consider this snippet:

import torch as to

def test_div() -> None:
    a: to.Tensor = to.arange(3)
    a.div_(2)
    assert to.equal(a, to.LongTensor([0, 0, 1]))

if __name__ == "__main__":
    test_div()

This snippet, which runs correctly, produces two mypy errors:

$ mypy  test.py
test.py:5: error: "Tensor" has no attribute "div_"
test.py:6: error: Too many arguments for "LongTensor"
Found 2 errors in 1 file (checked 1 source file)

The one way I found to suppress these errors is to pass --no-site-packages --ignore-missing-imports to the mypy invocation, but that has other side-effects that are not ideal.

Should type hints maybe be packaged separately until they are stable? How do people typically set up their projects to avoid these false positives?

Cheers,
Enrico

Hi,

We are dropping support for python 2 in January. After that, we will be able to add proper type annotations and run mypy in CI so that will be better.

In the meantime, I’m not sure how to silence specific errors in mypy :confused:

Hi,
thank you for the quick reply.

So far I couldn’t find a combination of flags that would ignore spurious errors coming from pytorch but would not hide any other actual error.

My two cents: it might be better to not distribute type hints at all rather than having them in, but half-broken: on the user side it becomes quite a pain.

Cheers,
Enrico

This is actually the first report I see of the type hints not working (maybe because very few people try to use them).
The main use case for them in the current code base is to make IDEs happy with pytorch and support auto-completion.

It could very well be that IDEs suppress errors, but checking a codebase that depends on pytorch with mypy does not work very well – e.g. the three simple lines above produce two errors.

I’m currently running mypy with --ignore-missing-imports --no-site-packages but I think that might suppress more than I’d like. I would like to opt out of pytorch type hints but apparently it’s not possible.

cc @smth is there someone that will take care of managing such problems when we move to python 3 only?

In case someone else stumbles upon this problem, this is the best I could do (suggested by the mypy devs on gitter):

[mypy]
# unrelated but typically required
ignore_missing_imports = True

[mypy-torch.*]
follow_imports = skip
follow_imports_for_stubs = True

Cheers,
Enrico

4 Likes