python import syntax

import can be used independently:

import module
import package

It can be used to import a module, a package, or . concated module/packages.

import package.module
import package1.package2
import package1.package2.module

But it can not be used to import a variable/function/class in a module:

#import module.var

To import a variable/function/class in a module, use “from… import…” statement instead:

from module import var
from package.module import var
from package1.package2.module import var
from package1 import package2
from package1.package2 import module

In “from…import” statement, “from” can be followed by module, package, or dot concated packages/module. But “import” can only be followed by var/function/class, module, or package. “import” can not be followed by dot concated packages/module/var.

#from package1 import package2.module
#from package import module.var
#from package1 import package2.module.var

It seems that from package, we can only import module. Actually, we can import var/function/class of module from package provided that the module imports the var/function/class  in its __init__.py.

#a.py
from package import var
print var

 

#__init__.py of package
from module import var
#import module

 

Consider the following situation:

#a.py
from package1 import package2
#print var
#print module.var
print package2.var
print package2.module.var

 

#__init__.py of package2
from module import var

Although __init__.py of package2 imports var in module and can use var directly, a.py can not use var directly. It must use package2. to access var, or use package2.module. to access var. If __init__.py changes to:

#__init__.py of package2
import module

a.py can only access var via package2.module.var.

import (whether the current script is executed by python or imported by another script) finds packages in current directory(the same directory as the script) before searching in sys.path. If the current script is imported by another script, this is equivalent to prefixing a dot before the imported package/module(the dot prefix is only valid in from…import, not in independent import):

from package import module
from .package import module
#import .package

The dot prefix can not be used by a script that is run by python(the main module), otherwise, you will get the following error:

ValueError: Attempted relative import in non-package

The dot-prefix form of “from…import” is called relative import. Every dot goes up one level of directory until the directory of the script run by python.

Leave a Reply