Search code examples
pythonpython-3.xpython-import

Why ModuleNotFound when importing a module in a same directory?


Question

When I try to activate main.py on linux bash with the command as follows,

python3 main.py

The error message looking as below keeps appearing, and I cannot figure out why!!

File "main.py", line 1, in <module>
    import folder_beta.util_one
File "folder_beta/util_one.py", line 1, in <module>
    ModuleNotFoundError: No module named 'util_two'

Questions in more detail

The folder tree looks like as below:

folder_alpha
├── main.py
└── folder_beta
      ├── __init__.py (empty)
      ├── util_one.py
      └── util_two.py

main.py

import folder_beta.util_one
import folder_beta.util_two
....

util_one.py

import util_two
...

When I executed the 'util_one.py' alone, it works perfectly fine but when I executed the main.py, the error keeps appearing.

Can anyone tell me how to fix this problem, please?


Solution

  • That is an implicit relative import, it would have worked in Python 2 but it's no longer allowed in Python 3. From PEP 8:

    Implicit relative imports should never be used and have been removed in Python 3.

    In util_one.py module, change it to:

    from folder_beta import util_two
    

    Explicit relative imports are also possible here, the equivalent would be:

    from . import util_two