My project file structure looks something like this:
hyphenated-project-root/
__init__.py
src/
__init__.py
module0.py
> from module1 import MyClass
> import module2
module1.py
> class MyClass: ...
module2.py
> from module1 import MyClass
scripts/
__init__.py
script1.py
> import module2
The __init__.py
files are empty and both module0.py
and script1.py
have __name__ == "__main__":
blocks. I'm using Python 3.9 on a Mac M1.
I would like to be able to run python src/module0.py arg1 arg2
as well as python scripts/script1.py
(or python -m scripts.script1
) from my terminal in the project root.
I've tried several variations of import module2
, modifying the __init__.py
files, nesting scripts/
under src/
and messing with import_module
from importlib
, but I keep getting ImportError
or ModuleNotFoundError
.
If possible, I would like to avoid modifying sys.path
. To a lesser extent, I would also like to avoid using setuptools
.
I know there are several SO questions/answers on this topic, but I can't figure out what I'm doing wrong. (My hunch is that Relative imports for the billionth time would be helpful for most others coming from Google.) Please advise.
Similar questions I've consulted:
- python import from sibling folder
- Relative imports for the billionth time
- What does from __future__ import absolute_import actually do?
- Importing files from different folder
- How to import python modules from sibling directory?
- Sibling package imports
- import module from a sibling directory in python3.10
Other resources I've consulted:
- https://blog.finxter.com/how-to-call-a-function-from-another-file-in-python/
- https://www.reddit.com/r/learnpython/comments/qynoc9/how_to_import_module_from_sibling_directory/
- https://answers.ros.org/question/227430/a-silly-question-about-packages-organization/
- https://github.com/tok3rat0r/siblingImports
- https://iq-inc.com/importerror-attempted-relative-import/
- https://techwithtech.com/importerror-attempted-relative-import-with-no-known-parent-package/
- https://www.datasciencelearner.com/importerror-attempted-relative-import-parent-package/