Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, VScode, Importing from sibling directory, without using os.paths.append - Python 3.8

python 3.8 with VScode. I have two sibling directories, and I want to import the first sibling (support_tools) to the second one.

this is my project hierarchy:

├── support_tools
│    ├── __init__.py
│    └── file_utils.py
└── optimizations
    ├──.vscode
    │    ├── launch.json
    │    └── settings.json
    ├── __init__.py
    └── test1.py

I added the parent path to the launch.json:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "env": {
                "PYTHONPATH": "${workspaceFolder}${pathSeparator}..${pathSeparator}",
            },
        }
    ]
}

and to the settings.json:

{
    "python.analysis.extraPaths": [
        "${workspaceFolder}/../"
    ]
}

The pylance recognize the module support_tools.py, but I cannot import the support_tools module without appending the parent path to the os.paths: sys.path.append("../")

In this tutorial: https://k0nze.dev/posts/python-relative-imports-vscode/ they clearly mention that after adding the paths to both file, I should be able to remove the os.path.append line

In addition I tried to find an answer in the following pages:

VSCode settings for Pylance

Import Sibling Packages with __init__.py doesn't work

Importing modules from parent folder

Thanks for the helpers

like image 265
Ilan Geffen Avatar asked Nov 04 '25 22:11

Ilan Geffen


1 Answers

enter image description here

A simple way is to use the optimizations parent folder as the workspace.

VsCode searches files using the workspace as the root directory. If the file you want to import is not in the workspace, it will not find the content.

Tips:

You can use the absolute path in "python. analytics. extraPaths".

Because in the workspace, the workspace is already the root directory. If you use the relative path, there does not exist the parent directory.

like image 113
MingJie-MSFT Avatar answered Nov 06 '25 11:11

MingJie-MSFT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!