> For the complete documentation index, see [llms.txt](https://nining.website/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nining.website/python/func/builtin-module/importlib.md).

# importlib

通过字符串名导入模块。你想导入一个模块，但是模块的名字在字符串里

```python
import importlib
math = importlib.import_module('math')
math.sin(2)

mod = importlib.import_module('requests')
mod.get('www.baidu.com')

# Same as 'from . import b'
b = importlib.import_module('.b', __package)
```

* import\_module只是简单地执行和import相同的步骤，但是返回生成的模块对象。你只需要将其存储在一个变量，然后像正常的模块一样使用
* 在旧的代码，有时你会看到用于导入的内建函数 \_\_import\_\_() 尽管它能工作，但是importlib.import\_module() 通常更容易使用
* [参考cookbook相关章节](https://python3-cookbook.readthedocs.io/zh_CN/latest/c10/p10_import_modules_using_name_given_in_string.html)
