Description
When I run mypy on my project, I sometimes get an invalid type error. This error seems to go away over time (some kind of caching issue?), or if I avoid having a file in a package of the same name, or if I do an explicit direct import of the type from the file instead of importing it via the package.
This is kind of a complicated bug to reproduce, but here is my best attempt at making a succinct repro. We will need five files.
-
Create a fresh virtual environment and test project directory.
mkvirtualenv repro --python=/usr/bin/python3 pip install mypy mkdir /tmp/whatever cd /tmp/whatever mkdir project
-
Have a
project/__init__.py
file containingfrom project.study import CustomType
-
Have an empty
project/root.py
file. -
Have a
project/neighbor/__init__.py
file containingfrom project.study import CustomType def m(arg: CustomType) -> str: del arg return 'test'
-
Have a
project/study/__init__.py
file containingfrom project.study.study import CustomType
-
Have a
project/study/study.py
file containingfrom project import root CustomType = str
Note: renaming this file to something that doesn't match its directory's name will cause the repro to fail.
-
(If you already ran mypy in this directory.) Clear the mypy cache.
rm -rf .mypy_cache
-
Run mypy on exactly these files in exactly this order.
mypy project/root.py project/study/study.py project/neighbor/__init__.py
-
And you will get this output:
project/neighbor/__init__.py:4: error: Invalid type "project.study.study.CustomType"
If you run mypy again without clearing its cache, then there will be no error.
or, depending on factors I don't understand you may get this different error instead:
project/neighbor/__init__.py:2: error: Internal error (node is None, kind=1)
An easy workaround for this issue is to avoid defining types in files that have the same name as their parent directory. Everyone likes avoiding cache invalidation issues by naming things, right?