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?

2

1 Answer 1

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 

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

from . import util_two 
Sign up to request clarification or add additional context in comments.

5 Comments

Should we write down "from folder_beta" even though util_one.py and util_two.py are in the same folder?
You can use explicit relative import as well, from . import util_two
@Eiffelbear You should consider your project structure when building the inner modules. The modules will all use the project root as path.
@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!
That's correct. This might be a good reading for you: stackoverflow.com/questions/14132789/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.