Python: Import Module

By Xah Lee. Date: . Last updated: .

Import Module

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

import os

# example of using a function
# get current dir
print(os.getcwd())
# 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")

print(xx.getcwd())
# 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
print(getcwd())

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/y.py. But the actual semantics is a bit complex.

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

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

Syntax: from x.y import *

from x.y import *

it does this:

If the file at x/y/__init__.py 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/a.py is imported as name a and the module at x/y/b.py is imported as name b.

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

Python: Paths and Module