Warn if mypy version doesn't match CI (#51799)

Summary:
This PR adds a local [`mypy` plugin](https://mypy.readthedocs.io/en/stable/extending_mypy.html#extending-mypy-using-plugins) that warns if you accidentally run `mypy` using a version that doesn't match [the version we install for CI](6045663f39/.circleci/docker/common/install_conda.sh (L117)), since this trips people up sometimes when `mypy` gives errors in some versions (see https://github.com/pytorch/pytorch/issues/51513) but not others.

Pull Request resolved: https://github.com/pytorch/pytorch/pull/51799

Test Plan:
To check that this doesn't break our `mypy` test(s) when you have the correct version installed:
```
python test/test_type_hints.py
```
To check that this does indeed warn when you have an incorrect `mypy` version installed, switch to a different version (e.g. 0.782), and run the above command or either of these:
```
mypy
mypy --config-file=mypy-strict.ini
```
You should get the following message on stderr:
```
You are using mypy version 0.782, which is not supported
in the PyTorch repo. Please switch to mypy version 0.770.

For example, if you installed mypy via pip, run this:

    pip install mypy==0.770

Or if you installed mypy via conda, run this:

    conda install -c conda-forge mypy=0.770
```

Reviewed By: janeyx99

Differential Revision: D26282010

Pulled By: samestep

fbshipit-source-id: 7b423020d0529700dea8972b27afa2d7068e1b12
This commit is contained in:
Sam Estep
2021-02-08 15:34:53 -08:00
committed by Facebook GitHub Bot
parent 21ef248fb8
commit dac730af11
3 changed files with 36 additions and 0 deletions

View File

@ -9,6 +9,7 @@
[mypy]
python_version = 3.6
plugins = mypy_plugins/check_mypy_version.py
cache_dir = .mypy_cache/strict
strict_optional = True

View File

@ -2,6 +2,8 @@
# test_run_mypy in test/test_type_hints.py uses this string)
[mypy]
plugins = mypy_plugins/check_mypy_version.py
cache_dir = .mypy_cache/normal
warn_unused_configs = True
warn_redundant_casts = True

View File

@ -0,0 +1,33 @@
import re
import sys
from pathlib import Path
from mypy.plugin import Plugin
def get_correct_mypy_version():
# there's probably a more elegant way to do this
match, = re.finditer(
r'mypy==(\d+(?:\.\d+)*)',
Path('.circleci/docker/common/install_conda.sh').read_text(),
)
version, = match.groups()
return version
def plugin(version: str):
correct_version = get_correct_mypy_version()
if version != correct_version:
print(f'''\
You are using mypy version {version}, which is not supported
in the PyTorch repo. Please switch to mypy version {correct_version}.
For example, if you installed mypy via pip, run this:
pip install mypy=={correct_version}
Or if you installed mypy via conda, run this:
conda install -c conda-forge mypy={correct_version}
''', file=sys.stderr)
return Plugin