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_functioninscript.pyand then either runningpython script.pyinside the directorysub_packageorpython sub_package/script.pyinside the directorymy_package. Either way, I get the error:
SystemError: Parent module '' not loaded, cannot perform relative import
- Using
from module import my_functionorfrom my_package.module import my_functionand runningscript.pyas above (either fromsub_packageormy_package). I get:
ImportError: No module named 'module'
(or similarly with my_package instead of module)
- Running
python -m sub_package/scriptfrom the directorymy_packageorpython -m my_package/sub_package/scriptfrom 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.