Python: Import Module

By Xah Lee. Date: . Last updated: .

Import Module

import moduleName
Load a module.
Call a function in module.
# import the standard module named os

import os

# example of using a function
# get current dir
# c:\Users\xah\.emacs.d\temp
xprefix = __import__(moduleNameStr)
Import a module, give it a prefix name.

Similar to import moduleName, but the moduleName is a string, and the prefix can be user defined. this is useful when you don't know the module name in advance, or when you want a different module name prefix.

# import the standard module os, assign it a prefix name

xx = __import__("os")

# c:\Users\xah\.emacs.d\temp

Import Function Names from Module

Module's function name can be imported directly by the syntax:

from moduleName import name_1, name_2, etc
Import several functions.
from moduleName import *
Import all functions.
from os import getcwd

# current dir

Detail on From-Import Statement

from x.y import z

Typically, this is used to import the name z, of single function z of module file at x/ But the actual semantics is a bit complex.

from x.y import z do ONE of two things:

If the module x/ doesn't have the name z, and there is no module at x/y/, then a ImportError is raised.

Syntax: from x.y import *

from x.y import *

it does this:

If the file at x/y/ defines a variable named __all__ (which should contain a list of strings, each string is a submodule name), then, all those sub-modules are imported. The names imported are the strings of __all__.

For example, if __all__ = ["a","b"], then the module at x/y/ is imported as name a and the module at x/y/ is imported as name b.

If __all__ is not defined, then from x.y import * just imports the name x.y (for module x/ and all names from module x/

Python: Paths and Module