How to solve "unresolved import" and "unable to import" messages in Python projects?

I opened a directory (on WSL Ubuntu) with VSCode with the following structure:

.
├── .vscode
│   ├── launch.json
│   └── settings.json
├── src
│   └── polls
│       ├── aiohttpdemo_polls
│       │   ├── db.py
│       │   ├── main.py
│       │   ├── routes.py
│       │   ├── settings.py
│       │   └── views.py
│       ├── config
│       │   └── polls.yaml
│       └── init_db.py
└── ve_websocket

I'm getting the warning message unresolved import ... when importing a file located in the same directory that the one calling it. Example: for routes.py

from views import index

def setup_routes(app):
    app.router.add_get("/", index)

I'm getting unresolved import 'views' Python(unresolved-import). Hence IntelliSense for index function does not work.

However IntelliSense suggests this notation:

from polls.aiohttpdemo_polls.views import index

with it the index function is recognized for IntelliSense now and no warning message appears, but when saving the file I get this error message Unable to import 'polls.aiohttpdemo_polls.views' pylint(import-error) now.

So I cannot run this script:

[polls]$ python init_db.py

My settings.json file has this configuration:

"python.pythonPath": "ve_websocket/bin/python3.8",
"python.linting.pylintEnabled": true,
"python.linting.pylintPath": "pylint",

Upvotes: 1

Views: 2593

Answers (1)

SOLUTION 1: settings.json

The solution is about using absolute imports (suggested by IntelliSense), and it is necessary to work with PYTHONPATH environment variable, so we need to add these lines to settings.json file for our workspace.

"terminal.integrated.env.linux": {
    "PYTHONPATH": "${workspaceFolder}/src",
},

After that, we open the terminal (from VSC) and need to confirm the changes, then reopen the terminal and we can run the script without errors, however VSC IDE still shows error marks on from keywords, overlook them, because objects being imported are recognized by IntelliSense with all their properties, and you can run your scripts without any problem.

SOLUTION 2: sys.path

The problem with the previous solution is that it works only when you are using the terminal from VSC. Hence you can use sys.path in every script needing to import objects. Example, for my init_db.py file:

import sys
from pathlib import Path
sys.path.append(str(Path.cwd().parent))

from sqlalchemy import create_engine, MetaData

from polls.aiohttpdemo_polls.settings import config
from polls.aiohttpdemo_polls.db import question, choice
... 

Upvotes: 1

Related Questions