How to use relative Import
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu May 16 19:39:34 EDT 2013
On Fri, 17 May 2013 01:35:49 +0530, Chitrank Dixit wrote:
> I want to know how relative imports are different than import. I have
> found lots of examples on internet explaining about the relative import
> but I want to know about the basic aspects of relative import that make
> it different than import.
Relative imports search the directory containing the current package,
absolute imports search the entire contents of sys.path. That is the only
difference.
The purpose of relative imports is to make it easy for modules inside a
package to import each other without worrying about other modules
*outside* the package being imported by mistake. You can read the PEP
here:
http://www.python.org/dev/peps/pep-0328/
to learn about the motivation for absolute and relative imports.
Optional in Python 2.5 and 2.6, and compulsory in 2.7, when you write:
import moduleX
Python looks at sys.path for a list of directories to search for
"moduleX.py". This is an absolute import.
But consider a package with this structure:
package/
+-- __init__.py
+-- moduleA.py
+-- moduleB.py
+-- moduleX.py
+-- subpackage/
+-- __init__.py
+-- moduleY.py
+-- moduleZ.py
Inside moduleA, if you write "import moduleX" it will be an absolute
import, the entire sys.path will be searched, and the "top level"
module.X will be found.
But if you write this instead:
from . import moduleX
you have a relative import, and Python will only search the current
package directory, so it will find the moduleX inside the package.
You can also write:
from .subpackage import moduleZ
to find the moduleZ inside the subpackage, again without searching the
entire sys.path.
Inside moduleY in the subpackage, all of these will find the same moduleZ:
# Relative to the current module:
from . import moduleZ
# Relative to the parent of the current module:
from ..subpackage import moduleZ
from .. import subpackage.moduleZ
# Absolute:
import package.subpackage.moduleZ
--
Steven
More information about the Python-list
mailing list