Josh Russo
Josh Russo

Reputation: 3241

VS Code Python import path when starting in a subfolder does not behave the same in VS Code and at run time

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

Answers (2)

Jill Cheng
Jill Cheng

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":

  1. Please add the following statement, which adds the path of the file to be imported to the system path, and VSCode can find her in the system path:
import os,sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

enter image description here

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.

enter image description here

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

Andrew Clark
Andrew Clark

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

Related Questions