如何使用__import__函数从子模块导入名称? [英] How to use the __import__ function to import a name from a submodule?
问题描述
我正在尝试使用__import__
函数复制from foo.bar import object
,但似乎遇到了麻烦.
I'm trying to replicate from foo.bar import object
using the __import__
function and I seem to have hit a wall.
一个简单的案例from glob import glob
很简单:glob = __import__("glob").glob
A simpler case from glob import glob
is easy: glob = __import__("glob").glob
我遇到的问题是我正在从子包中导入名称(即from foo.bar
):
The problem I'm having is that I am importing a name from a subpackage (i.e. from foo.bar
):
所以我想要的是类似的东西
So what I'd like is something like
string_to_import = "bar"
object = __import__("foo." + string_to_import).object
但这只是导入了顶级foo
包,而不是foo.bar
子包:
But this just imported the top-level foo
package, not the foo.bar
subpackage:
__import__("foo.bar")
<module 'foo' from 'foo/__init__.pyc'>
推荐答案
__import__
函数将返回包的顶级模块,除非您传递了非空的fromlist
参数:
The __import__
function will return the top level module of a package, unless you pass a nonempty fromlist
argument:
_temp = __import__('foo.bar', fromlist=['object'])
object = _temp.object
请参见 __import__
函数上的Python文档.
See the Python docs on the __import__
function.
这篇关于如何使用__import__函数从子模块导入名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!