Analogue's Blog

home

Python import from import usage

24 Oct 2011

Python import from import usage

Here's a quick note to understand how works the Python module importing engine.

Suppose you have a package with the following hierarchy:
package/subpackage/module.py

Each package and subpackage has an empty __init__.py file to define it as a package, and the module.py has a small function defined:
def function():
    print "Works!"

If you are running a script at the same level as the main package, here's what you can do:
import package.subpackage.module
package.subpackage.module.function()
from package.subpackage import module
module.function()
from package.subpackage.module import function
function()

And what you cannot do:
import package.subpackage
package.subpackage.module.function()
import package.subpackage.module.function
package.subpackage.module.function()

I hope it helps!

Comments