Reputation: 436
I'm running vscode from some project/
folder and getting an "unresolved import" error in some project/impl/
folder. In the impl/
folder I have 2 Python files:
# lib.py
class A():
pass
# run.py
from lib import A # vscode error here - unresolved import
...
When running run.py
the Python interpreter finds the lib
just fine but vscode shows an "unresolved import" error (screenshot).
If I change the import line to from .lib import implementation
(note the dot), I get the opposite behaviour where vscode resolves the import fine but the Python interpreter fails.
How should I import the lib or otherwise configure vscode to resolve imports from a local folder? (obviously I don't want to add the exact path of the local folder to the vscode config file since I would have to do so for every subfolder in the project)
Upvotes: 3
Views: 7101
Reputation: 10344
When I used the python extension version 2018.12.1 in my computer, I got the same issue as you described.
Since this function is provided by the language service, and the python language service is provided by the python extension, it is recommended that you could try to use the latest version of the python extension(2020.8.106424).
In addition, you could use the extension "Pylance", which also provides excellent language services for python.
The project I created on my computer:
My environment:
VSCode Version: 1.48.2 (user setup)
OS: Windows_NT x64 10.0.18362
Python extension: 2020.8.106424
languageServer in settings.json
:
"python.languageServer": "Pylance",
Update1:
When the language service I use is "Jedi
", the code also does not have this warning:
"python.languageServer": "Jedi",
Update2:
Since this warning does not affect the execution result of the code, we could also turn off this kind of warning in the settings (settings.json
):
"python.analysis.disabled": [
"unresolved-import"
]
In this way, we can use "python.languageServer": "Microsoft",
Upvotes: 7
Reputation: 436
You can add the folder to path of module searching for python using sys module.
import sys
sys.path.insert(1, "./impl/")
from lib import A
Note, the vs code can still underline the import line, but, it will work just fine when you run the program. Give it a try!
You can add more paths like this -
sys.path.insert(n, <path to folder>)
Keep care to use a new natural number in place of n for every new path.
Upvotes: 1