Same import, different errors

孤者浪人 提交于 2021-01-29 15:33:12

问题


I am making tests for my code, but I'm facing a strange import error.

Notes:

  • I am using VSCode version: 1.46.1
  • PYTHONPATH is set to project's root

Folder structure is this:

-app.py
-models
---language.py
---category.py
-my_tests
---unit
------models
---------category_test.py
---------language_test.py

In category_test, I do import "Category" class by using:

from models.category import Category

In language_test, I do import "Language" class by using:

from models.language import Language

In category_test case, all works fine.
In language_test case, I encounter one "Import error".
Instead of searching at the project's root as it does for category_test file, it searches on my_test/unit/models folder.

When i print sys.path, result is as expected:

[
 '/home/ste3/Documents/Projects/SteFunBot/my_tests/unit/models', -> current folder
 '/home/ste3/Documents/Projects/SteFunBot', -> PYTHONPATH
 '/usr/lib/python38.zip', '/usr/lib/python3.8', 
 '/usr/lib/python3.8/lib-dynload', 
 '/home/ste3/Documents/Projects/SteFunBot/venv/lib/python3.8/site-packages'
]

How can I fix this?

EDIT
I think it is a linter issue. Can it be? If I try to import the moudules by specifying the path from root (step1) and then I recover the import removing the root from the import path (step2), it works:
Step 1

from SteFunBot.models.language import Language

Step 2

from models.language import Language

回答1:


When importing modules (files) in other folders, VSCode starts from the parent folder of the file by default. Therefore, we can help VSCode find the module path in the following ways:

  1. Use absolute paths. The way to set the VSCode search path is to start from the current project. VSCode first changes to the project folder path before executing the code.

    For example: Use

    "env": {
                    "PYTHONPATH": "D:\\...\\folder"
                }
    

    in "launch.json" to add the absolute path of the project:

  2. Use relative paths. Find the project path based on the relative path of the file (using the imported module file), then VSCode will start searching from the project folder.

    For example: Use the following code at the beginning of the file to find the project folder path:



来源:https://stackoverflow.com/questions/65182339/same-import-different-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!