I have a project structured like this:
. └── myapp ├── app.py ├── models │ ├── hello.py │ └── world.py └── requirements.txt
I have two models, hello
and world
. Both models are used from app.py
where I import them like this:
from models.hello import Hello from models.world import World
But world
also needs to use hello
. I tried this in world.py
:
from models.hello import Hello
The above technically works when I run the app, but VSCode's Python extension gives me the following error:
E0401:Unable to import 'models.hello'.
What is the proper way of importing a submodule from the same directory? How do I avoid this error in VSCode?
How do I fix pylint import error? Solution 1: (configure workspace settings to point to fully qualified python executable): Solution 2: (open VS Code from an activated virtual environment): Cause: The path to the python executable is incorrect.
Relative imports make use of dot notation to specify location. A single dot means that the module or package referenced is in the same directory as the current location. Two dots mean that it is in the parent directory of the current location—that is, the directory above.
Absolute vs Relative Imports in Python There are two types of relative imports: implicit and explicit. Relative imports make use of dot notation to specify location: A single dot means that the module or package referenced is in the same directory as the current location.
The error you are receiving is one that's reported by a python linter named pylint
. So the problem isn't really specific to the vscode extension.
There are two solutions:
Please try adding an .env
file in your project directory with the vape PYTHONPATH=./myapp
, this will tell pylint where to find your modules
Or just open the folder myapp
in vscode directly instead of opening the parent directory in vscode.
The error is coming from pylint. You need to add this line into settings.json file (VS Code):
"python.linting.pylintArgs": ["--init-hook", "import sys; sys.path.append('<absolute path to myapp directory>')"],
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With