This turned out to be rather complicated. mypy has an exclude option, but it only affects automatic discovery. This has several limitations:
- If a module is imported by another module then it is still checked, even if listed in exclude. This is a know mypy misfeature.
- pytest specifies each file to test, and this again overrides the exclude (which is not surprising).
To fix the first problem I changed __init__.py to not import version.py if type checking. It's ugly, but necessary.
To fix the second problem I added --ignore-glob=*version.py to pytest addopts in setup.py.
I also added exclude = version\.py to the mypy section. It is not needed to run pytest, but helps if anyone wants to run mypy from the command line.
Perhaps we should make version.py mypy-compliant, but fundamentally I think we should not be checking version.py, especially mypy is a moving target; code that passes at one time may fail for a newer version. We can pin the version of mypy we use, but it's much easier to coordinate changes within a package to the pinned version of mypy than it is to track changes to the code that generates the version.py file.