gpt4 book ai didi

Python 的 __import__ 不能按预期工作

转载 作者:IT老高 更新时间:2023-10-28 20:38:56 24 4
gpt4 key购买 nike

当使用带点名称的 __import__ 时,例如:somepackage.somemodule,返回的模块不是 somemodule,无论返回什么似乎大多是空的!这是怎么回事?

最佳答案

来自 __import__ 上的 python 文档:

__import__( name[, globals[, locals[, fromlist[, level]]]])

...

When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned. This is done for compatibility with the bytecode generated for the different kinds of import statement; when using "import spam.ham.eggs", the top-level package spam must be placed in the importing namespace, but when using "from spam.ham import eggs", the spam.ham subpackage must be used to find the eggs variable. As a workaround for this behavior, use getattr() to extract the desired components. For example, you could define the following helper:

def my_import(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod

转述:

当您请求 somepackage.somemodule 时,__import__ 返回 somepackage.__init__.py,通常为空。

如果您提供 fromlist 它将返回 somemodule(您想要的 somemodule 中的变量名称列表,实际上并未返回)

您也可以像我一样使用他们建议的功能。

注意:我问这个问题完全是想自己回答。我的代码中有一个大错误,并且误诊了它,我花了很长时间才弄明白,所以我想我会帮助 SO 社区并在这里发布我遇到的问题。

关于Python 的 __import__ 不能按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/211100/

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