C. E.
C. E.

Reputation: 10627

Loading modules in the same Python package

I have a directory structure like this:

myPackage /
    __init__.py
    module1
    module2
    module3
    ...

Some of these modules depend on other modules in the package. For some reason, I find that importing from e.g. module1 in module2 does not work if I write it like this:

from module1 import func1, func2, ...

This says that there is no module named module1, I can' figure out why... Is this not supposed to work? Are there any known pitfalls that could cause this problem? And is there a different approach to load modules in the same package that is preferred?

Upvotes: 1

Views: 72

Answers (2)

Sraw
Sraw

Reputation: 20234

Well, I'd like to explain a little bit more.

Every python program has one and only one global hierarchical module management. The modules in sys.path are the top modules. So take your code as example:

root
----myPackage
--------module1 <- this is what you want.
--------module2
----module1 <- this does not exist.

Although you load module1 in module2, it still need to obey current module management which starts outside the package.

This design is used to ensure singleton on modules. All imported modules are cached in sys.modules, so to uniquely identify one module, all modules are managed based on hierarchy.

Another example:

In module2:

from myPackage import module1

And in your main file:

from myPackage import module2
import sys
print(sys.modules)

You will see one module named myPackage.module1, although it is imported in myPackage.module2, but it isn't named as myPackage.module2.myPackage.module1.

Upvotes: 2

lxop
lxop

Reputation: 8625

module1 isn't on your path, so from module1 import xyz will not work (because module1 can't be found).

You can either update the imports to

from myPackage.module1 import xyz

or

from .module1 import xyz

The second one is nice in that it avoids duplicating the package name inside the package, but it will mean that you can't easily execute your module1 directly (e.g. python module1.py). If you don't need to execute it directly, then no problem.

Upvotes: 2

Related Questions