I have:
foo/
├── __init__.py
├── bar.py
└── baz
├── __init__.py
└── alice.py
In bar.py, I import Alice, which is an empty class with nothing in it but the name attribute set to "Alice".
from baz.alice import Alice
a = Alice()
print(a.name)
This runs properly:
$ python foo/bar.py
Alice
But mypy complains:
$ mypy --version
mypy 0.910
$ mypy --strict .
foo/bar.py:1: error: Cannot find implementation or library stub for module named "baz.alice"
foo/bar.py:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
Found 1 error in 1 file (checked 6 source files)
Why is mypy complaining?
mypy has its own search path for imports and does not resolve imports exactly as Python does and it isn't able to find the baz.alice module. Check the documentation listed in the error message, specifically the section on How imports are found:
The rules for searching for a module
fooare as follows:The search looks in each of the directories in the search path (see above) until a match is found.
- If a package named
foois found (i.e. a directory foo containing an__init__.pyor__init__.pyifile) that’s a match.- If a stub file named
foo.pyiis found, that’s a match.- If a Python module named
foo.pyis found, that’s a match.
The documentation also states that this in the section on Mapping file paths to modules:
For each file to be checked,
mypywill attempt to associate the file (e.g.project/foo/bar/baz.py) with a fully qualified module name (e.g.foo.bar.baz).
There's a few ways to solve this particular issue:
from foo.baz.alice import Alice), and then running from a top-level module (a .py file in the root level).# type: ignore to the import line.MYPYPATH variable to point to the foo directory:(venv) (base) ➜ mypy foo/bar.py --strict
foo/bar.py:3: error: Cannot find implementation or library stub for module named "baz.alice"
foo/bar.py:3: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
Found 1 error in 1 file (checked 1 source file)
(venv) (base) ➜ export MYPYPATH=foo/
(venv) (base) ➜ mypy foo/bar.py --strict
Success: no issues found in 1 source file