I am trying to import a module from a sibling package in Python; following the instructions in this answer. My problem is that the import works… but mypy
is saying that it’s a bad import. I’m seeking to understand why mypy is reporting an error, and how to fix it.
Directory structure/Code
This is a module that I have installed successfully with python -m pip install -e .
. I know it is installed because it is listed when I run pip freeze
, and the project root is listed in sys.path
when I print that out.
mypackage ├── mypackage │ ├── foo │ │ ├── __init__.py │ │ └── db.py │ ├── bar │ │ ├── __init__.py │ │ └── model.py │ └── py.typed └── setup.py
In db.py:
from mypackage.bar import model
In model.py:
class MyClass: # implementation irrelevant
Error Message
When I run mypy (mypy mypackage
from the project base directory), I get the following error:
mypackage/foo/db.py:7: error: Module 'mypackage.bar' has no attribute 'model'
What confuses me is that, when I open IDLE, the following imports/runs just fine:
>>> from mypackage.bar import model >>> model.MyClass <class 'mypackage.bar.model.MyClass'>
My Question
Why is mypy showing an error here when the import actually works? How can I get mypy to recognize that the import works?
Advertisement
Answer
Running mypy with the --namespace-packages
flag made the check run without error, which pointed me to the actual problem: ./mypackage/mypackage/__init__.py
did not exist, causing mypy
to not pursue the import correctly. Python was working because in 3.3+, namespace packages are supported, but mypy requires a flag to check for those specifically.
Thus, my overall solution was to add the needed __init__.py
file.