Consider the following scenario:
test_setup/
├── __init__.py
├── helper.py
└── main.py
helper.py
is:
def helper_func():
print('helping')
main.py
is:
from helper import helper_func
def main_func():
helper_func()
if __name__ == '__main__':
main_func()
__init__.py
is:
from .main import main_func
I would like to be able to do two things:
1.run main
from within the package. This works.
2.import main_func
for use outside this package. This doesn't work. When called from the parent directory of test_setup
,
from test_setup import main_func
yields:
In [1]: from test_setup import main_func
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-1-c395483f58c8> in <module>
----> 1 from test_setup import main_func
~/PycharmProjects/test_setup/__init__.py in <module>
1 #from .helper import helper_func
----> 2 from .main import main_func
~/PycharmProjects/test_setup/main.py in <module>
----> 1 from helper import helper_func
2
3 def main_func():
4 helper_func()
5
ModuleNotFoundError: No module named 'helper'
If I change the first line in main.py
to a relative import from .helper import helper_func
that works, but fails when I just try to run from within the package (goal 1 above) yielding:
Traceback (most recent call last):
File "/Users/xxx/PycharmProjects/test_setup/main.py", line 1, in <module>
from .helper import helper_func
ImportError: attempted relative import with no known parent package
What's going on here, and how do I fix things to achieve goals 1 and 2? Trying to import helper_func
in __init__.py
didn't help either.
The following failed as well:
In [1]: from test_setup.main import main_func
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-1-764832db473f> in <module>
----> 1 from test_setup.main import main_func
~/PycharmProjects/test_setup/__init__.py in <module>
----> 1 from .main import main_func
~/PycharmProjects/test_setup/main.py in <module>
----> 1 from helper import helper_func
2
3 def main_func():
4 helper_func()
5
ModuleNotFoundError: No module named 'helper'