Python imports various subpackages with the same root package name and different locations

I was wondering if anyone could shed some light on this. We have several package libraries with one root package, for example. a . I also have ab package located in X and ac package located in Y. And X and Y are in my PYTHONPATH , and when I do:

 import ac import ab 

I get an error: "No module named b" . After reading it, it seems to me that when ac loads, the python writes information about a , and when I come to do ab , because he has information about a , he will never bother to look at location X for ab and gives an error so that there isn’t No modules found with the name b .

In addition, I found that the order in which X and Y are specified in PYTHONPATH seems to affect imports. For example, when I do

 PYTHONPATH=$PYTHONPATH:X:Y python >>> import ab # works >>> import ac # fails 

But if I do

 PYTHONPATH=$PYTHONPATH:Y:X python >>> import ab # fails >>> import ac # works 

Is it right, and if so, how can I get around this? It is convenient to have a common root module name and different subpackages in different projects, etc. Of course, I come from a Java point of view where you can do such an overlap.

+6
source share
1 answer

I found a related question, but lost the link to it.

The solution is to include:

 from pkgutil import extend_path __path__ = extend_path(__path__, __name__) 

in the root directory __init__.py in all . In this case, in a/__init__.py BOTH in places X and Y. If you have several levels of subpackages, you still need to enable it only once.

This helped me and the documentation for extend_path and info. What is __path__ useful for?

+6
source

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


All Articles