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

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

问题描述

我正在尝试使用 __import__ 函数从 foo.bar 导入对象 复制 ,但我似乎碰壁了.

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天全站免登陆