Reputation: 3241
I have a sample Python application that I'm playing around with in VS Code. The folder structure that I have is that the application is in a sub-folder. The readme.md and code-workspace files and the like are in the root of the project, and then I have a sub-folder for my application code.
I have a file that represents the entry point of the application, and other files containing supporting logic in the same folder. When I try to import from those files VS Code wants me to put a period before the module (file) name.
from .my_code_file import my_class
But that errors when I run the application. It runs just fine if I remove the leading period.
from my_code_file import my_class
Why does VS Code Intelisense think I need a period in front of the module name?
This is a representation of the file and folder structure:
|-AppCode
| |-my_code_file.py
| |-application_entry_point.py
|
|-readme.md
|-MyProject.code-workspace
Upvotes: 2
Views: 2371
Reputation: 10372
The reason is that when importing other files, the standard import statement should be: "from AppCode.my_code_file import my_class
", and VScode starts from the parent folder of the currently opened file by default. Obviously, VSCode cannot find the folder "AppCode
" from the folder "AppCode
", we can use the following two methods to help VSCode find "my_code_file
":
import os,sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
If Pylint
reports an error "Unable to import'AppCode.my_code_file
", but the code can run, we can use
"python.linting.pylintArgs": [
"--disabled=E0602"
]
to turn off this warning.
2.We can also use "from my_code_file import my_class
", the code can be executed to get the result.
If Python
reports an error "unresolved import'my_code_file
", but the code can run, we can use
"python.analysis.disabled": [
"unresolved-import",
],
to close this warning.
Reference: readable-pylint-messages.
Upvotes: 2
Reputation: 880
I was running into issues just like this recently and after some googling I found several ppl recommending I download microsoft's new Python extension called Pylance.
I've been using it for about a week and it solved all of my issues I was having that involved my application being confused w/ file structure. I'd recommend giving it a try! https://marketplace.visualstudio.com/items?itemName=ms-python.vscode-pylance
Cheers, -Andrew
Upvotes: 1