Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing From Sister Subdirectories in Python?

Tags:

python

import

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)?

like image 522
Eli Avatar asked May 03 '13 06:05

Eli


People also ask

Can import Python file from same directory?

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.

How do you use relative import in Python?

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.

Does Python search subdirectories for imports?

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.


1 Answers

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.

like image 169
Amber Avatar answered Oct 03 '22 17:10

Amber