首页 > 解决方案 > 你可以在 Python 中执行内联导入吗?

问题描述

假设您只想在代码中调用一次正则表达式。据我所知,这意味着您需要import re在从re. 是否可以将它与函数调用结合起来,内联?我想也许这样的事情会起作用

print(import re; re.search(r'<regex>', <string>).group())

但它只是在导入时抛出一个错误,说明语法无效。这让我相信,做到这一点的唯一方法是

import re
print(re.search(r'<regex>'), <string>).group())

标签: pythonimport

解决方案


回答问题:

您可以在 Python 中执行内联导入吗?

您可以使用内置importlib模块:

print(importlib.import_module('re').search("h", "hello").group())

输出:

'h'

当然,它需要您先导入importlib模块:

import importlib

print(importlib.import_module('re').search("h", "hello").group())

文档中:

import_module()函数充当importlib.__import__(). 这意味着函数的所有语义都源自importlib.__import__(). 这两个函数最重要的区别是import_module()返回指定的包或模块(例如pkg.mod),而__import__()返回顶级包或模块(例如pkg)。


推荐阅读