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_import
forpy2
- 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 bar
is different among where it used.- In
baz.py
it will importsbar.py
, - In
foo/baz.py
it 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 .bar
Import in function discussion
import
will cache the module. Soimport in function
won't cause reload and severe overhead.- But
import in function
would still have addtional overhead for checking and resolving the cache, etc. - So, use
import in function
only for optional library support or resolving circular dependency problem. import
statement 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
item
is defined in the package; - If not, it assumes it is a module and attempts to load it.
- If it fails to find it, an
ImportError
exception 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.