Python Glossary Русский

all Python 3importlibfunction

importlib.import_module()

importing by name

Imports a module whose name is given as a string and returns the module object — for instance a plugin whose name comes from a config file.

Syntax

module = importlib.import_module(name, package=None)

Unlike __import__('a.b'), which returns the top-level package a, import_module('a.b') returns a.b itself. The function binds no name — assign the result. A relative name such as '.sub' needs package=, otherwise TypeError. The module runs only once: a repeated call takes it from sys.modules instead of re-reading the file.

Examples

import importlib
m = importlib.import_module('json.decoder')
print(m.__name__)  # → json.decoder
print(__import__('json.decoder').__name__)  # → json
print(importlib.import_module('.decoder', package='json') is m)  # → True
import importlib
try:
    importlib.import_module('.decoder')
except TypeError as e:
    print('TypeError')  # → TypeError — нужен package=
try:
    importlib.import_module('no_such_module')
except ModuleNotFoundError as e:
    print(e)  # → No module named 'no_such_module'

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy