I have the following structure of python code:
.
├── my_main.py
└── my_pkg
├── my_dep.py
├── my_script.py
Both my_main.py
and my_script.py
should be callable (have a if __name__ == '__main__'
) section:
my_main.py:
import my_pkg.my_script
if __name__ == '__main__':
print(my_pkg.my_script.bar())
and my_script.py:
import my_dep
def bar():
return my_dep.foo() + 1
if __name__ == '__main__':
print(bar())
this imports ... my_dep.py:, which looks like:
def foo():
return 1
If you want to look at it all together, look here: https://github.com/ct2034/python_import_trouble
Problem:
If I run
my_script.py
, all works well.But if I run
my_main.py
, I get:ModuleNotFoundError: No module named 'my_dep'
If I change the import in
my_script.py
tofrom . import my_dep
,my_main.py
works.But when I run
my_script.py
, I get:ImportError: attempted relative import with no known parent package
How can I make both of them work?
Note: This is on Python 3.8
And sorry for the long-winded explanation. Was not able to make it any more concise. Hope it is understandable.