How to use relative Import

C

Chitrank Dixit

Hello Python developers

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.


*Regards
*
*Chitrank Dixit
*
*IIPS-DAVV
*
*Indore (M.P.) , India *
*MCA
*
*trackleech.blogspot.in*
 
S

Steven D'Aprano

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,202
Latest member
MikoOslo

Latest Threads

Top