python - 将 "sub"模块导入为自己的 "sub"模块

标签 python import module

假设您有一个包foo,其中包含以下__init__.py:

from bar import *

其中 bar 是使用 pip install bar 安装的任何 python 模块。

现在,当您可以导入 bar 时,总是有效的:

from bar import submodule #works
import bar.submodule      #works, too

现在我假设以下事情全部也能正常工作:

from foo import submodule     # a) is possible
import foo.submodule          # b) not possible ("no module named submodule")
from foo.bar import submodule # c) also impossible ("no module named submodule")

为什么它们不可能?从 foo 维护者的角度来看,我需要做什么才能使它们成为可能?

最佳答案

submodulebarfoo 模块对象的成员,而不是它的子模块。因此,它们的行为就像 foo 的任何其他成员属性一样。您可以使用 from foo import ... 形式将它们引入第三个模块的模块命名空间,但不能直接相对于 foo import 它们。我想如果你手动将它们侵入到所需名称下的 sys.modules 中,你就可以做到,但你真的不应该做这样的事情......

为了说明这个问题:

foo.py

# x and y are values in the foo namespace, available as member attributes
# of the foo module object when foo is imported elsewhere
x = 'x'
y = 'y'

bar.py

# the foo module object is added as a member attribute of bar on import
# with the name foo in the bar namespace
import foo
# the same foo object is aliased within the bar namespace with the name
# fooy
import foo as fooy
# foo.x and foo.y are referenced from the bar namespace as x and y,
# available as member attributes of the bar module object
from foo import x, y
# z is a member attribute of the bar module object
z = 'z'

baz.py

# brings a reference to the x, y, and z attributes of bar (x and y
# come in turn from foo, though that's not relevant to the import;
# it just cares that bar has x, y, and z attributes), in to the
# namespace of baz
from bar import x, y, z
# won't work, because foo is a member of bar, not a submodule
import bar.foo
# will work, for the same reason that importing x, y, and z work
from bar import foo

关于python - 将 "sub"模块导入为自己的 "sub"模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14586366/

相关文章:

python - 如何从另一行加上新数据在 pandas 数据框中创建行

python - 无法打开由 Python 中的线程创建的管道描述符

python 字符串赋值

Scala:如何始终使某些实用程序可用于子包?

无法解析 javax.servlet.http.HTTPServlet 导入,而包的其余部分导入正常

jquery - 使用ajax和django传递信息

actionscript-3 - 在纯 Actionscript 3 项目中将 .swc Assets 加载到数组中

python - 遍历给定目录中的 python 文件并导入它们?

python - Python 有包/模块管理系统吗?

zend-framework - 未捕获的异常 'Zend_Controller_Dispatcher_Exception' 和消息 'Invalid controller class ("Error_ErrorController")