python - 你可以在 Python 中执行内联导入吗?
问题描述
假设您只想在代码中调用一次正则表达式。据我所知,这意味着您需要import re
在从re
. 是否可以将它与函数调用结合起来,内联?我想也许这样的事情会起作用
print(import re; re.search(r'<regex>', <string>).group())
但它只是在导入时抛出一个错误,说明语法无效。这让我相信,做到这一点的唯一方法是
import re
print(re.search(r'<regex>'), <string>).group())
解决方案
回答问题:
您可以在 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)。
推荐阅读
- java - Apache Ignite:让客户端访问本地机器上的 Ignite 服务器,而不是集群中的任何机器
- reactjs - 如何验证用户键盘输入的输入值?
- gradle - 使用 gradle 和 jfrog 工件插件如何将通用工件上传到通用存储库
- angular - 是否可以按需构建模块?
- c# - 在选择语句中传递参数时,npgsql 不返回行
- prometheus - 如何让 Prometheus 根据 Alert 标签向两个不同的 Alertmanagers 发送 Alerts?
- c++ - 我可以在堆分配的原始数组上使用 std::sort 吗?
- xaml - Ribbon.xaml 上的定向控件
- reactjs - 在使用 PDF.JS 渲染所有 pdf 页面时,列表中的每个孩子都应该有一个唯一的“key”道具
- arrays - VBA 数组中的 IF 语句比循环更快地运行代码