Here's my directory structure:
my_package
|
+--__init__.py
|
+--setup.py
|
+--module.py
|
+--sub_package
|
+--__init__.py
|
+--script.py
The script script.py
needs to import a function from module.py
, and I need to be able to run script.py
using the Python interpreter.
I know that Guido calls this an "anti-pattern". And I know you have 10 reasons why I shouldn't do this. I probably agree with most of them - really, I do. I wouldn't be asking this question if I could avoid this. So can we just skip the part where we go over why this is bad and move on to the solution? Thanks!
I also know that there are about a 1000 other SO questions about this. I've probably read them all by now. Most of them were made obsolete by changes to Python's import system, and the rest just aren't right.
What I have tried:
- Using
from .module import my_function
inscript.py
and then either runningpython script.py
inside the directorysub_package
orpython sub_package/script.py
inside the directorymy_package
. Either way, I get the error:
SystemError: Parent module '' not loaded, cannot perform relative import
- Using
from module import my_function
orfrom my_package.module import my_function
and runningscript.py
as above (either fromsub_package
ormy_package
). I get:
ImportError: No module named 'module'
(or similarly with my_package
instead of module
)
- Running
python -m sub_package/script
from the directorymy_package
orpython -m my_package/sub_package/script
from the parent directory ofmy_package
. I get:
No module named sub_package/script
(or similarly with my_package/sub_package/script
)
Is there anything else I should be trying? I would really rather avoid messing with sys.path
or PYTHONPATH
for a whole host of reasons.