0

I'm using VS code and a conda venv. I have created a folder called "project" and in the folder I have 3 sub folders "helper", "function", "function2". Now I have a helper_function.py in folder "helper" where I have defined several functions and I want to import them in my function code where I have a main.py.

project/
    helper/
        __init__.py
        helper_function.py
    function/
        __init__.py
        main.py
    function2/
        __init__.py

I'm always receiving the error:

from helper.helper_function import date_conf
ModuleNotFoundError: No module named 'helper'

I have already created a blank __init__.py in the helper folder but it's still the same.

AzUser1
  • 183
  • 1
  • 14

3 Answers3

0

You have at least 3 possibilities:

  • create a setup.py, run and install you package
  • modify your PYTHONPATH in VSCode settings or shell session
  • update your sys.path before imports

If you're using VSCode, the simplest is probably to update your PYTHONPATH in settings, assuming you have a linux terminal:

"terminal.integrated.env.linux": {"PYTHONPATH": "${PYTHONPATH}:${workspaceFolder}/helper:${workspaceFolder}/function:${workspaceFolder}/function2"}
matleg
  • 618
  • 4
  • 11
0

helper directory must be same level as "main.py" (considering your current working directory is where main.py located).

i suggest you read this to get familiar with relative and absolute imports.

0

Add the following code above the import statement:

import sys
sys.path.append("./")

enter image description here

If you don't want to modify the code, you can also use the following method:

  • Add the .env file in the workspace.

Note that the file name only has an extension. If it is modified, additional settings are required.

.env file:

PYTHONPATH = "E:\\Desktop\\project"
  • Add the following configuration in launch.json
            "env": {
                "PYTHONPATH": "E:\\Desktop\\project"
            }

Both of the above need to execute the script in debug mode.

enter image description here

enter image description here

JialeDu
  • 6,021
  • 2
  • 5
  • 24