Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper relative imports: "Unable to import module"

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?

like image 638
Jimmy Sanchez Avatar asked Feb 25 '18 13:02

Jimmy Sanchez


People also ask

How do I fix Pylint import error?

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.

How do you use relative import in Python?

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.

What is a relative import?

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.


2 Answers

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:

  1. Please try adding an .env file in your project directory with the vape PYTHONPATH=./myapp, this will tell pylint where to find your modules

  2. Or just open the folder myapp in vscode directly instead of opening the parent directory in vscode.

like image 50
Don Avatar answered Sep 20 '22 06:09

Don


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>')"], 
like image 26
Shtefan Avatar answered Sep 23 '22 06:09

Shtefan