pythonvisual-studio-codemodulenotfounderror

ModuleNotFoundError issue with importing functions


I'm facing an issue with importing functions from a file within my working directory in Python using VSC. Here's my setup:

my_project/
├── __init__.py
├── subfolder/
│   ├── __init__.py
│   └── helper_functions.py
└── workingfolder/
    ├── __init__.py
    └── working_script.py

In working_script.py (located in workingfolder), I am trying to import my_function() from helper_functions.py using the following import statement:

from subfolder.helper_functions import my_function

However, I’m getting a

ModuleNotFoundError: No module named 'subfolder' 

when I try to run working_script.py.

I’ve made sure that both subfolder and workingfolder contain __init__.py files, as well as the root directory (my_project/). Despite these steps, I’m still unable to import the function properly. Can anyone help me troubleshoot what might be going wrong?

Thanks in advance for any help or advice!


Solution

  • Add a main.py in the top directory (my_project) that imports what it needs to start the program. Instead of running the other scripts alone, just call whatever function you're trying to test in main.py. Then your imports can be uniform, as they will all start from the top project directory. This is better practice as a whole, especially for large programs.

    Additionally, I've seen many Python programs with an src file and all of the .py files inside. This alliviates the need to use parent directories and nested directories as well.