Python 内置函数 `__import__`

来自 Python 3 文档

此函数由 import 语句调用。它可以被替换 [...] 以更改 import 语句的语义,但这强烈不被推荐,因为通常使用 import hooks [...] 更简单。直接使用 __import__() 也不被推荐,应优先使用 importlib.import_module()。

简介

__import__() 函数是 import 语句调用的底层函数。虽然可以直接使用它,但这通常是不被推荐的。对于动态导入模块,推荐使用 importlib.import_module() 函数。

示例

以下是如何使用 __import__() 动态导入 math 模块的示例:

# 动态导入 'math' 模块
math_module = __import__('math')

# 现在可以像使用常规导入一样使用它
print(math_module.sqrt(4))
2.0

然而,使用 importlib 的推荐方式是:

import importlib

math_module = importlib.import_module('math')
print(math_module.sqrt(4))
2.0

相关链接