[SOLVED] VSCode Import Quick Fixes always Relative to ${workspaceFolder}

Issue

This Content is from Stack Overflow. Question asked by Thomas Matecki

I’m working on a python project within a pretty large multi-language mono-repo with VSCode’s python tools (pylance). The root of the workspace(/repo) is not the root module of python imports.

When attempting to “Quick-Fix” an undefined variable, the language server is able to resolve it and find an import path, but the proposed import is relative to the root of the workspace.

For example, I may be working on a file:

${workspaceFolder}/backend/src/saasbox/api/auth/serializers.py

… and need to import something from:

${workspaceFolder}/backend/src/saasbox/api/modules/identity.py

… Ideally the proposed import module would be:

import Thing from saasbox.api.modules.identity

BUT it is import Thing from backend.src.saasbox.api.modules.identity, which isn’t what I want. Is there any setting to change this?



Solution

Solution one:

Add the following configuration in settings.json file

    "python.analysis.extraPaths": [
        "./backend/src"
    ],

Solution two:

Use VS code to open the backend folder instead of the workspace folder.

Example:

The file structure is as follows

workspace
└─ backend
   └─ src
      └─ saasbox
         └─ api
            ├─ auth
            │  └─ serializers.py
            └─ modules
               └─ identity.py

Now use VS code to open the workspace folder, add the above configuration to settings.json, and get the quick import as follows

enter image description here


If I use vsod to open backend as a workspace (remove the config just added), the resulting imports are as follows

enter image description here

enter image description here

Why is the import that opens backend as workspace not including src?

src is a special folder, and there is a default enabled setting in VS code to add src to the import path.

enter image description here

So the second solution above could also be:

Move the src folder under the current workspace, making it the first level folder under the workspace.

enter image description here


This Question was asked in StackOverflow by Thomas Matecki and Answered by JialeDu It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?