Can modules with a common package hierarchy be mentioned repeatedly in my PYTHONPATH?

I have two separate projects that have a common package name. They work fine until they are both on PYTHONPATH, but as soon as they both appear, one of them cannot find the import in their own project.

Example: two projects:

Project 1:

x/
  __init__.py
  test.py
  foo.py

test.py contains the line:

import x.foo

Project 2:

x/
  __init__.py
  bar.py

If I run

PYTHONPATH=. python x/y/test.py

no error. But if I run

PYTHONPATH='pathtoproject2:.' python x/test.py

I get an error message:

Traceback (most recent call last):
  File "x/test.py", line 1, in <module>
    import x.foo
ImportError: No module named foo

Is there a way to have different Python projects with a common package sharing PYTHONPATH? Or will Python always use only the first path where the package will be found?

Note. I know if you change the import from x.foo to import foo then it will work. But I want to know if this can be done without modifying the package.

+5
2

Python . - , . "" Java " " .NET.

Python sys.path, . , , , .

"", , . import foo, Python test.py, , foo, , ImportError.

, , , . Python , , , , . org.example.foo org.example.bar foo bar.

+3

, python. __init__.py.

try:
    import pkg_resources
    pkg_resources.declare_namespace(__name__)
except ImportError:
    import pkgutil
    __path__ = pkgutil.extend_path(__path__, __name__)

pkg_resources python setuptools , , zip .

pkgutil python, , , setuptools .

python :

http://packages.python.org/distribute/setuptools.html#namespace-packages

http://www.python.org/dev/peps/pep-0382/

+2

All Articles