So, I've seen a few similar questions on Stack Overflow, but nothing seems to address my issue, or the general case. So, hopefully this question fixes that, and stops my headaches. I have a git repo of the form:
repo/
__init__.py
sub1/
__init__.py
sub1a/
__init.py
mod1.py
sub2/
__init__.py
mod2.py
How do I import mod2.py from mod1.py and vice versa, and how does this change depending on whether mod1.py or mod2.py are scripts (when each respectively is importing-- not being imported)?
Make an empty file called __init__.py in the same directory as the files. That will signify to Python that it's "ok to import from this directory". The same holds true if the files are in a subdirectory - put an __init__.py in the subdirectory as well, and then use regular import statements, with dot notation.
Relative imports use dot(.) notation to specify a location. A single dot specifies that the module is in the current directory, two dots indicate that the module is in its parent directory of the current location and three dots indicate that it is in the grandparent directory and so on.
The PYTHONPATH is the environment variable that contains the path of the directories that Python searches to import the packages. Therefore, if we add the subdirectory to the PYTHONPATH , Python will first look at the directories in PYTHONPATH and import it from there.
The simplest solution is to put the directory containing repo
in your PYTHONPATH
, and then just use absolute-path imports, e.g. import repo.sub2.mod2
and so on.
Any other solution is going to involve some hackery if you want it to cover cases where you're invoking both the python files directly as scripts from arbitrary directories - most likely sys.path
mangling to effectively accomplish the same thing as setting PYTHONPATH
, but without having to have the user set it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With