I have package in following structure
Main_file
__init__.py
main.py
sub_folder
__init.py
a.py
b.py
b.py contain
def print_value():
print("hello")
a.py contain
import b
b.print_value()
in main.py
from sub_folder import a
when i run main.py i got following error
No module named 'b'
2 Answers 2
Since sub_folder is not in your PYTHONPATH, you need to use a relative import from a.py:
from . import b
b.print_value()
Sign up to request clarification or add additional context in comments.
Comments
You can also include the sub_folder into the system path by
import sys
sys.path.append(<path to sub_folder>)
Note: as observed in the comments below, this can create issues due to double loads. This works for scripts, and is not the right method to use when writing packages.
answered Oct 13, 2018 at 9:54
Arjun Venkatraman
2392 silver badges10 bronze badges
2 Comments
zvone
The result of that would be having two versions of each module: there would be module
a and module sub_folder.a, with same contents, but treated by Python as two separate modules. Sometimes it does not matter, when you encounter bugs caused by this, they will be rather ugly bugs ;)Arjun Venkatraman
Thanks for the pointer! I was thinking from the point of view of writing a script, rather than a package!
lang-py