Forgive me for another "relative imports" post but I've read every stack overflow post about them and I'm still confused.
I have a file structure that looks something like this:
|---MyProject
| |---constants.py
| |---MyScripts
| | |---script.py
Inside of script.py
I have from .. import constants.py
And of course when I run python3 script.py
, I get the error ImportError: attempted relative import with no known parent package
.
From what I understand, this doesn't work because when you run a python file directly you can't use relative imports. After hours of searching it seems that the most popular solution is to add "../"
to sys.path
and then do import constants.py
but this feels a little hacky. I've got to believe that there is a better solution than this right? Importing constants has got to be a fairly common task.
I've also seen some people recommend adding __init__.py
to make the project into a package but I don't really understand how this solves anything?
Are there other solutions out there that I've either missed or just don't understand?