1

How do I make one package reference another package, but make it look like the referenced package belongs to the initial package?

package_1
|
|____ __init__.py

package_2
|
|____ __init__.py
|____ module_1.py

Inside package_1.__init__.py is

# __init__.py
import package_2

Now the following calls works fine:

>>> import package_1
>>> print package_1
<module <module 'package_1' from  '...\package_1\__init__.pyc'>

>>> from package_1 import package_2
>>> print package_2
<module 'package_2' from '...\package_2\__init__.pyc'>

>>> print package_2.module_1
<module 'package_2.module_1' from '...\package_2\module_1.pyc'>

>>> from package_2 import module_1
>>> print module_1
<module 'package_2.module_1' from '...\package_2\module_1.pyc'>

But I want to be able to do this:

>>> from package_1.package_2 import module_1

But I get:

Traceback (most recent call last):
    File "testfile.py", line 15, in <module>
        from package_1.package_2 import module_1
ImportError: No module named package_2

The reason I want to do this is because package_2 used to be a subpackage of package_1. Now that package_2 is it's own package, I want to be able to reference it from package_1 to keep the behaviour as it was before.

4

1 に答える 1