Import from Sister subdirectories in Python?

So, I saw several similar questions about stack overflow, but nothing seems to affect my problem or general case. So, I hope this question fixes this and stops my headaches. I have a git repo form:

repo/ __init__.py sub1/ __init__.py sub1a/ __init.py mod1.py sub2/ __init__.py mod2.py 

How to import mod2.py from mod1.py and vice versa, and how does it change depending on whether mod1.py or mod2.py are scripts (when each of them imports is not imported)?

+6
source share
3 answers

The simplest solution is to place the directory containing the repo in your PYTHONPATH , and then just use the absolute path import, for example. import repo.sub2.mod2 etc.

Any other solution will be connected with some hackers if you want it to cover cases when you call python files directly as scripts from arbitrary directories - most likely sys.path in order to efficiently perform the same as installing PYTHONPATH , but without having to install it by the user.

+6
source

If you are using Python 2.6+, you have two options:

  • Relative imports
  • Adding repo to your PYTHONPATH

For relative imports, special point syntax is used:

in package sub1:

 from .sub2.mod2 import thing 

in sub1a package:

 from ..sub2.mod2 import otherthing 

Note that simple import module do not work with relative imports.

A better solution would be to use absolute import with the correct Python path (example in bash ):

 export PYTHONPATH=/where/your/project/is:$PYTHONPATH 

Additional Information:

+2
source

A script or module can import modules that either

  • on the system path or
  • part of the same package as the importing script / module.

For modules, these rules apply without exception. Rules apply for scripts, but the wrinkle is that by default when you run the script it is not considered part of the package.

This means that by default, a script can only import modules that are in the system path. By default, the path includes the current directory, so if you run the script, it can import the modules in the same directory or in packages that are subdirectories. But it is so. A script does not have the concept of โ€œwhere is itโ€ in the directory tree, so it cannot do imports that require certain relative information about the path to the subdirectories. This means that you cannot import things "from the parent directory" or "from the directory for sisters." Things that are in these directories can only be imported if they are on the way to the system.

If you want to make the script "know" that is in the package, you can assign the __package__ attribute to __package__ . See this previous question . Then you can use explicitly relative imports (e.g. from ...sub2 import mod2 ) from within the script.

0
source

Source: https://habr.com/ru/post/944176/


All Articles