Search code examples
pythonmoduleimporterror

How do I import a module within the same directory or subdirectory?


I have the following directory for a project:

photo_analyzer/
│
├── main.py                # Main script to run the photo analyzer
├── gui/                   # Directory for GUI-related files
│   ├── __init__.py        # Package initialization
│   ├── app.py             # Tkinter application class and main GUI logic
│   ├── widgets.py         # Custom Tkinter widgets (if needed)
│   ├── styles.py          # Styling configurations for the GUI
│   └── resources/         # Directory for GUI resources (e.g., icons, images)
│       ├── icon.png       # Application icon
│       └── ...
│
├── photo_analysis/        # Directory for photo analysis-related files
│   ├── __init__.py        # Package initialization
│   ├── photo_utils.py     # Utility functions for photo manipulation
│   ├── light_profiles.py  # Functions to analyze light profiles in photos
│   └── ...

I'm trying to import photo_utils and light_profiles from the photo_analysis module into gui/app.py. Whenever I try to run app.py, I get the following error message:

Traceback (most recent call last):
  File "c:\Users\Josh\Documents\PhotoAnalyzer\gui\app.py", line 6, in <module>
    from photo_analysis import photo_utils
ModuleNotFoundError: No module named 'photo_analysis'

I have empty __init__.py files in both directories, so I don't think that's the issue. I've tried adding the photo_analysis module to the Python path using SET PYTHONPATH="C:\Users\Josh\Documents\PhotoAnalyzer\photo_analysis" and I've tried to use the sys.path technique as well. Both end with the same error message as before.

photo_utils.py imports widgets.py from the "gui" module. Could I be experiencing circular dependency? I did try the work-around explained in text by importing widgets into each method in photo_utils that used it, and while this allowed a test main code in photo_utils to run properly, app.py still gives the same error message that there is no module named 'photo_analysis'.

What am I missing?


Solution

  • It is a tricky one. Normally python imports from their sibling files or childs of sibling folders. Here if you want to import from a file that are from same parent then you have to use sys.path.append('.')

    Secondly it also depends on the terminal current working directory. If your current working directory is "photo_analyzer" then adding these line will work

    import sys
    sys.path.append('.')
    import photo_analysis.photo_utils as pa
    

    Otherwise if your current working directory is "photo_analyzer/gui", then you have to add these lines

    import sys
    sys.path.append('./../photo_analysis')
    import photo_utils as pa