Skip to content
Advertisement

Sibling package import and mypy “has no attribute” error

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.

JavaScript

In db.py:

JavaScript

In model.py:

JavaScript

Error Message

When I run mypy (mypy mypackage from the project base directory), I get the following error:

JavaScript

What confuses me is that, when I open IDLE, the following imports/runs just fine:

JavaScript

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement