Detailed documentation(PEP328) on Python’s importing standards are provided here.
In this post, we will go over the following concepts:
- Multi-line import
- Absolute import
- Relative import
The first rule is that multi-line imports can be wrapped with a paranthesis.
from Tkinter import (Tk, Frame, Button, Entry, Canvas, Text, LEFT, DISABLED, NORMAL, RIDGE, END)
If you have a module named ‘string.py’, when you do,
you would not know whether the Python’s standard ‘string.py’ library is being imported or your private module is being imported. The absolute imports are recommended to avoid this ambiguity.
In Python 3, the absolute import is set to the default. However, in Python 2, you need to manually enable the absolute import.
from __future__ import absolute_import
In the following package structure,
package/ __init__.py subpackage1/ __init__.py moduleX.py moduleY.py subpackage2/ __init__.py moduleZ.py moduleA.py
when you want to import a function in moduleX.py from moduleA.py, you would use,
from package.subpackage1.moduleX import a_function
Even though this import statement is residing within moduleA.py, Python import will search upward the directory structure until you find a package named ‘package’, and traverse down.
This absolute import syntax is more explicit and readable, and it has been suggested to use absolute imports over the traditional relative import
When you use relative imports, the import statement does not require the actual name of package structure anymore. It instead focuses on the physical structure of the package.
In the following package structure, package/ init.py subpackage1/ init.py moduleX.py moduleY.py subpackage2/ init.py moduleZ.py moduleA.py
Assuming that the current file is either moduleX.py or subpackage1/init.py , following are correct usages of the relative imports:
from .moduleY import spam from .moduleY import spam as ham from . import moduleY from ..subpackage1 import moduleY from ..subpackage2.moduleZ import eggs from ..moduleA import foo from ...package import bar
There are some cases where a relative import has benefits compared to an absolute import. The most important of which is being able to rearrange the structure of large packages without having to edit sub-packages. This is actually highly encouraged in building Django web application, since you can use your Django application in a modular manner.