ModuleNotFoundError: No module named 'x' when trying to run my code

43 Views Asked by At

Really at my wits end, tried multiple solutions including using a setup.py file, changing relative imports to absolute imports and vice-versa, package restructuring, ensuring each package as an __init__.py file and more. Any help would be appreciated. I have simplified my project below.

My project structure is as follows:

myProject
   |
   |__ src
        |
        |__ foo
        |     - __init__.py
        |    |
        |    |__ bar
        |          - __init__.py
        |         |
        |         |__ baz
        |              - __init__.py
        |              - baz_functions.py
        |              - baz_watch.py
        |
        | - __init__.py
        | - project_code.py
        | - main.py

As for the files:

main.py

import project_code

if __name__ == '__main__':
    project_code.run()

project_code.py

import foo.bar.baz.baz_functions

def run():
    print('Hello World!')

baz_watch.py

from baz_functions import function_1, function_2

print('Watching...')

baz_functions.py

def function_1():
   print('I am function 1')

def function_2():
   print('I am function 2')

Naturally, without the: import foo.bar.baz.baz_functions in project_code.py, the code runs just fine.

The error I get is:

Traceback (most recent call last):
  File "C:\xxx\xxx\xxx\myProject\src\main.py", line 1, in <module>
    import project_code
  File "C:\xxx\xxx\xxx\myProject\src\project_code.py", line 1, in <module>
    import foo.bar.baz.baz_functions
  File "C:\xxx\xxx\xxx\myProject\src\foo\bar\baz\baz_watch.py", line 1, in <module>
    from baz_functions import function_1, function_2
ModuleNotFoundError: No module named 'baz_functions'
2

There are 2 best solutions below

1
chepner On BEST ANSWER

baz_functions is not a top-level module; it lives in the package foo.bar.baz and, using an absolute import, has to be imported as such.

A relative import can use . to refer to a module in the same package as the importing module:

from .baz_functions import function1, function2
1
Abhijith On

In your baz_watch.py file, you have to import baz_functions using relative import (adding . before module name). By doing this, you are telling python to look for the module in the same directory as your baz_watch.py file. Otherwise it may look for the package in your python path and throw error. Here is the modified code.

from .baz_functions import function_1, function_2

print('Watching...')