Reputation: 79
I have a multi-directory project. I use absolute imports for each directory. For example,
main_dir | | - sub_dir1 | | - a.py (has say class A) | - sub_dir2 | | - b.py (imports class A. Syntax: from subdir1.a import A)
When I run it in the terminal, from main_dir, it works fine. However, this import gives me an "unresolved import 'differential_diagnosis.src.algorithm'Python(unresolved-import)" in VS code. I do not know how to fix this.
The biggest challenge I face because of this is that I cannot use the peek feature to look at what the member functions of class A do.
I have raised a similar ticket on GitHub Project.
Upvotes: 1
Views: 3722
Reputation: 8411
Try to add these codes in your python file:
import sys
print(sys.path)
The interpreter only can search these paths to find modules. Python will only automatically add the folder which contains the current python file to sys.path
.
'The path of 'sub_dir1' should not be found in sys.path
. You need to add these settings in launch.json file:
"env": {
"PYTHONPATH": "${workspaceFolder}"
},
Then your workspace path will be added to sys.path
.
If main_dir is the workspace folder, then you can change from subdir1.a import A
to from main_dir.subdir1.a import A
.
If not, it should be changed to from {workspaceName}.{folder}....main_dir.subdir1 import A
, and you should add a __init__.py
file in every folder to change the folder to a python package.
Upvotes: 4
Reputation: 3305
You should place some code of what you are trying to do. What I can say is that Python looks for modules in the import search path. First it looks for built-in modules, Python looks in the sys.path variable which is initialized by the directory of the original script + PATH shell variable + some installation dependent default.
See: https://docs.python.org/3/tutorial/modules.html
To guarantee that your imports can be found, you can do:
sys.path.append(pathname_to_module)
just before you import a module.
Upvotes: 0