Python的导入无法按预期工作

2024-06-16 11:02:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 模块import名称somepackagesomemodule
3条回答

python 2.7具有importlib,点路径按预期解析

import importlib
foo = importlib.import_module('a.dotted.path')
instance = foo.SomeClass()

来自__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社区解决这个问题,把我遇到的问题贴在这里。

有一个更简单的解决方案,如文档中所述:

如果您只想按名称导入模块(可能在包中),可以调用“导入”,然后在sys.modules中查找它:

>>> import sys
>>> name = 'foo.bar.baz'
>>> __import__(name)
<module 'foo' from ...>
>>> baz = sys.modules[name]
>>> baz
<module 'foo.bar.baz' from ...>

相关问题 更多 >