1

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?

Eiffelbear
  • 399
  • 1
  • 4
  • 23
  • Does this answer your question? [Import a module from both within same package and from outside the package in Python 3](https://stackoverflow.com/questions/47319423/import-a-module-from-both-within-same-package-and-from-outside-the-package-in-py) – MisterMiyagi Jan 28 '20 at 17:30
  • When you run `main.py`, your package root path is `folder_alpha`. When `util_one.py` try to `import util_two.py`, it is trying to find `util_two` in `folder_alpha` path. Since it doesn't exist, Python returns a `ModuleNotFoundError`. – r.ook Jan 28 '20 at 17:42

1 Answers1

2

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
wim
  • 338,267
  • 99
  • 616
  • 750
  • Should we write down "from folder_beta" even though util_one.py and util_two.py are in the same folder? – Eiffelbear Jan 28 '20 at 17:41
  • 1
    You can use explicit relative import as well, `from . import util_two` – r.ook Jan 28 '20 at 17:43
  • @Eiffelbear You should consider your project structure when building the inner modules. The modules will all use the project root as path. – r.ook Jan 28 '20 at 17:49
  • @r.ook So the . in `from . import util_two` tells `util_one.py` to look up the `util_two.py` in the same directory, `folder_beta`, rather than upper directory, `folder_alpha`! – Eiffelbear Jan 28 '20 at 17:51
  • 1
    That's correct. This might be a good reading for you: https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time – r.ook Jan 28 '20 at 18:50