Table of Contents

Absolute import vs implicit, explicit relative import discussion


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, not things like foo/ To import foo/, there are two ways. One is absoulte import and the other is explicit relative import.

from __future__ import absolute_import

# Absolute import

# 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__]