如何使用__import__函数从子模块导入名称? [英] How to use the __import__ function to import a name from a submodule?

查看:80
本文介绍了如何使用__import__函数从子模块导入名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用__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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆