gpt4 book ai didi

python - 在 Python 中动态加载模块中的所有名称

转载 作者:太空宇宙 更新时间:2023-11-04 03:36:25 24 4
gpt4 key购买 nike

如何from some.module import *,其中模块的名称是在字符串变量中定义的?

最佳答案

此代码从 os 导入所有符号:

import importlib
# Load the module as `module'
module = importlib.import_module("os")
# Now extract the attributes into the locals() namespace, as `from ..
# import *' would do
if hasattr(module, "__all__"):
# A module can define __all__ to explicitly define which names
# are imported by the `.. import *' statement
attrs = { key: getattr(module, key) for key in module.__all__ }
else:
# Otherwise, the statement imports all names that do not start with
# an underscore
attrs = { key: value for key, value in module.__dict__.items() if
key[0] != "_" }
# Copy the attibutes into the locals() namespace
locals().update(attrs)

参见例如this question有关 from ... import * 操作背后逻辑的更多信息。

虽然这有效,但您不应该使用此代码。从命名模块导入所有符号已经被认为是不好的做法,但使用用户给定的名称执行此操作肯定更糟糕。如果您需要有关可能出错的提示,请搜索 PHP 的 register_globals

关于python - 在 Python 中动态加载模块中的所有名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28826127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com