PYTHONPATH hell with overlapping packet structures

I am having problems with PythonPath on Windows XP, and I am wondering if I am doing something wrong.

Say I have a project (created with Pydev) that has an src directory. In src , I have one package named common , and in it there is one class module named service.py with the class name Service

Say now that I have another project (also created using Pydev) with the src directory and shared package. In the general package, I have one script, client.py , which imports the service.

Thus, in other words, two separate disk space, but the same package.

I noticed that even if I set my PYTHONPATH to include both src directories, the import will fail if the files are not in the same directory. I get a scary module.

I don't understand how python resolves module names? I'm used to Java and its infernal class.

+3
source share
3 answers

If you really have a split package like this, read the __path __ level attribute.

In short, make one of the src directories primary and give it __init__.py, which adds the path to the other "src" to the __path__ list. Now Python will look in both places when looking for the 'src' submodules.

I really do not recommend this in the long run. It is kind of fragile and breaks if you move things around.

+2
source

I think in Python you better avoid this problem by giving each package a unique name. Do not name both packages common . Then you can import both with something like

 import common1.service as cs import common2.client as cc 
+1
source

If you try to import like this:

 import src.common.service 

Python will look for the Python path for the directory named "src" (or egg, etc.). When he finds "src", he will not consider another. If the first "src" does not have a common and service inside it, you will get an ImportError, even if there are these things in the other "src" directory.

+1
source

All Articles