将“sub”模块导入为自己的“子”模块

时间:2013-01-29 15:27:27

标签: 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维护者的角度来看,我需要做些什么来使它们成为可能?

1 个答案:

答案 0 :(得分:2)

submodulebarfoo模块对象的成员,而不是它的子模块。因此,它们的行为与foo的任何其他成员属性相同。您可以使用from foo import ...表单将它们带入第三个模块的模块名称空间,但不能直接import它们相对于foo。我想如果你手动将它们以所需名称砍入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