What I have tried
First let me say, I have read maybe 5 or 6 other stackoverflow questions related to this and many things have been said about this. Here's what I found and what I tried:
"Do
sys.path.append(<root dir>)
before other imports."Issue: This works, but it's against PEP standard practice so I'd rather find a solution that does not require modifying
sys.path
."Use the
imp
library to find your module."Issue: The solution outlined in that answer is deprecated as
importlib
is the newimp
, and I'm not sure how to useimportlib
even after looking at the docs."Add an empty
__init__.py
file in your root directory."Issue: This does not work.
Details of my problem
Here is my file structure:
Project/
├ subdir/
| └ script.py
├ __init__.py
└ module.py
(Note that I left the empty __init__.py
file in there just in case it's needed.)
I'm trying to import from module.py
to subdir/script.py
:
Contents of module.py
:
def func():
print('func was called')
Contents of subdir/script.py
:
from module import func
func()
However, when I run python3 script.py
in terminal (on Mac), I get this error message:
Traceback (most recent call last):
File "script.py", line 1, in <module>
from module import func
ModuleNotFoundError: No module named 'module'
I would appreciate a straightforward solution that does not require modifying sys.path
.