pythonpathpython-module

ModuleNotFoundError: No module named 'src' even after adding path


I'm attempting to import some functions from src, but I keep getting the error "ModuleNotFoundError: No module named 'src'". I've added src to the path, but to no avail. Here is my directory structure:

my-project
  -- src
      -- __init__.py
      -- file1.py
  -- notebooks
      -- __init__.py
      -- current_notebook.ipynb

In current_notebook.ipynb, I am calling from src.file1 import *. However, whenever I try to run it I get an error. I've added src to my path using sys (sys.path.insert(0, '/path_to_desktop/my_project/src') and tried export PYTHONPATH="${PYTHONPATH}:/path_to_desktop/my-project/src, but it is still not working. Does anyone have any idea what the problem might be?


Solution

  • My guess is that you should just add your project path to sys.path rather than the path to the src module.

    Here is what it would look like:

    import os
    import sys
    
    # get the project path dynamically to avoid hardcoded path
    project_path = os.path.abspath(os.path.join('..'))
    
    # check the path is not already in sys.path, to avoid duplicates
    if project_path not in sys.path:
        sys.path.insert(0, project_path)
    
    from src.file1 import *
    

    PS: This article has a clear and concise description of how the modules are found and imported.