Import

Table of Contents

Absolute import vs implicit, explicit relative import discussion

foo
  |--__init__.py
  |--bar.py
  |--baz.py
bar.py
baz.py

This would cause subtle bugs. At this point, we need absolute_import

from __future__ import absolute_import
import bar

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

def foo():
    global math
    import math

Submodules related from

from package import item
  1. Tests whether the item is defined in the package;
  2. If not, it assumes it is a module and attempts to load it.
  3. If it fails to find it, an ImportError exception is raised.
import item.subitem.subsubitem
  1. Each item except for the last must be a package
  2. 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.

Sorting imports

Get a reference to the current module howto

import sys
current_module = sys.modules[__name__]