5

I switched from PyCharm to VSCode. Now, I have a problem importing a modules within the same package.

main.py

from importlib_resources import files

import household_prices.data.raw_data as raw_data # <- moudle not found

source = files(raw_data).joinpath("household_price.csv")
df = pd.read_csv(source)

I think it has to do with the python path. When I call sys.path in PyCharm, I have both ~/code/household_prices/household_prices/analysis and ~/code/household_prices/household_prices.

The second path is missing in VSCode. Is there an automated way to always incude the root of the package in the python path?

folder structure

* household_prices
  * .idea
  * household_prices
    * analysis
      * __init__.py
      * main.py
    * data/
      * __init__.py
      * raw_data/
        * __init__.py
        * household_price.csv
    * README.md
Molitoris
  • 935
  • 1
  • 9
  • 31

2 Answers2

1

According to your description, it is recommended that you could try the following tips:

  1. Add the line of settings to the launch.json file of .vscode file:

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

VSCode will automaticCally look in the root of the project.(the outermost household_prices),

then, VSCode will further look for the required file based on this line of code:

import household_prices.data.raw_data.

  1. Create '__init__.py' file in folder household_prices(the Second floor), it will let VSCode know more accurately that a file is a package.

I have created a project with the same structure as your file, and after testing, I can successfully import the module.

My environment:python3.8.3; VSCode: 1.47.3; OS: Windows_NT x64 10.0.18362

Jill Cheng
  • 9,179
  • 1
  • 20
  • 25
  • I think the line should be "env": {"PYTHONPATH" : "${workspaceRoot}/household_prices"}, – atlau Jul 31 '20 at 10:12
  • I thought about that before, but VSCode will find the root directory( household_prices) of the current project according to ""${workspaceRoot}"}. After I try to add '/household_prices', it shows that there is no such module. – Jill Cheng Aug 03 '20 at 04:39
  • 1
    I did try this solution but this is not working for me. The path is never added. – Stefano Paviot Apr 12 '21 at 14:10
0

One way is to set the PYTHONPATH environment variable to the folder where your modules are. For example I work with projects where the packages are either under app/ or backend/, so I export the variable in my ~/.bashrc:

export PYTHONPATH=./backend:./app

This way no matter what I open VS Code will also try to load the packages from the two subdirectories from the current directory.

Another solution could be the use of env files setting the PYTHONPATH.

But I feel this question is already answered elsewhere: How to add to the PYTHONPATH in Windows, so it finds my modules/packages?

atlau
  • 881
  • 1
  • 7
  • 16