Python: Import Module

By Xah Lee. Date: . Last updated: .

Import Module

import moduleName

Load a module.

once a module is loaded, functions in the module can be called by:

moduleName.functionName

import os

# example of calling a imported function
# get current dir
print(os.getcwd())
# c:\Users\xah\.emacs.d\temp

Import a Module at Runtime, and Using Alias Prefix

xprefix = __import__(moduleNameStr)

Import a module, give it a prefix name.

Similar to import moduleName, but the moduleName is a string.

The xprefix can be anything.

This is useful when you know the module name only at runtime, 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 os import getcwd

# current dir
print(getcwd())
from moduleName import *

Import all functions.

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