jakes
jakes

Reputation: 2095

How to setup VSCode to be able to import files from child directory

@KindNotice: I've searched the current treads like this one or this one for potential solution. However, I still have troubles to gather every information together and find the optimal and working setup. Although my case is probably less general, it tries to connect the dots from different places at SO. Please take this into consideration before marking as a duplicate.

My project is structured like this:

my-project/
  src/
    model.py
    utils.py
    __init__.py
  notebooks/
    test.py

In model.py I have an import:

from utils import my_function

My working directory is set to my-project (as returned by os.getcwd()). I am using Conda environment, and tried to amend PYTHONPATH as suggested here with:

"env": {"PYTHONPATH": "${workspaceRoot}, ${workspaceRoot}/src"}

I also have __init__.py within my src directory. From my understanding, if I use from src.utils import my_function it would work fine within VSCode - however, when running from bash terminal from the src directory (where the model.py script is located). To add to all of that I'd like to be able to import my modules in jupyter notebook files located in notebooks.

What's the best setup to be able to import scripts from another modules from src here? Is editing PYTHONPATH really neccesary here? (I can't see any effect of that).

Upvotes: 3

Views: 6189

Answers (1)

Jill Cheng
Jill Cheng

Reputation: 10372

When importing modules (files) in other folders, VSCode starts from the parent folder of the file by default.

The way I import and use the classes and methods of files in other files in VSCode is as follows:

  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:

import os,sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

Run:

enter image description here

enter image description here

enter image description here

Upvotes: 3

Related Questions