3

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:

Other resources I've consulted:

michen00
  • 764
  • 1
  • 8
  • 32
  • This question really deserves an answer. It's unbelievable how complicated this is in Python, and most of the answers provided elsewhere don't work for Python 3.9. – David Cian Feb 06 '23 at 17:10

0 Answers0