Python modules import problem: import statement in different location

Viewed 37

Here's my folder structure:

main.py
tools/
  sub1.py
  sub2.py

where main.py:

import tools.sub1
import tools.sub2

and sub1.py:

a = 'abc'

and sub2.py (directly import sub1 is not working, is it because I am running main.py from the root directory?):

import tools.sub1
print(tools.sub1)

from here, I knew that in order to correctly call sub1, sub2 from main, we have to add the statement import tools.sub1 in sub2, however, if I want to run sub2 individually, error occurs

Traceback (most recent call last):
  File "sub2.py", line 1, in <module>
    import tools.sub1 as sub1
ModuleNotFoundError: No module named 'tools'

So, My question is that is it possible to directly run sub2 individually, while keeping the current design that we can properly run main.py?. Thanks in advance.

2 Answers

You can do this by making tools a python module. Adding an __init__.py file (can be empty) in your tools directory will make Python consider the "tools" folder a module. You can then reference sub1 from both main.py and sub2.py with:

from tools import sub1
Related