Import
Table of Contents
- Absolute import vs implicit, explicit relative import
- Import in function
- Submodules related from
- Sorting imports
- Get a reference to the current module
Absolute import vs implicit, explicit relative import discussion
from __future__ import absolute_importforpy2- Default in
py3
foo
|--__init__.py
|--bar.py
|--baz.py
bar.py
baz.py
- In
implicit relative import, which is legacy and not recommended, the semantic ofimport baris different among where it used.- In
baz.pyit will importsbar.py, - In
foo/baz.pyit will importsfoo/bar.py
- In
This would cause subtle bugs. At this point, we need absolute_import
With this code, import bar always imports bar.py, not things like foo/bar.py. To import foo/bar.py, there are two ways. One is absoulte import and the other is explicit relative import.
from __future__ import absolute_import
# Absolute import
import foo.bar
# Explicit relative import
# This is valid only when this file is in 'foo' package
# This way is discouraged; PEP8 prefers absolute imports
import .barImport in function discussion
importwill cache the module. Soimport in functionwon't cause reload and severe overhead.- But
import in functionwould still have addtional overhead for checking and resolving the cache, etc. - So, use
import in functiononly for optional library support or resolving circular dependency problem. importstatement is just loading a module and giving a name for it. So we can perform a module level import within a function:
Submodules related from
from package import item- Tests whether the
itemis defined in the package; - If not, it assumes it is a module and attempts to load it.
- If it fails to find it, an
ImportErrorexception is raised.
- Tests whether the
import item.subitem.subsubitem- Each item except for the last must be a package
- The last item can be a module or a package but can’t be a class or function or variable defined in the previous item.