了解包结构(模块 X.Y 没有属性 Z)

Understanding the package structure (Module X.Y has no attribute Z)

这是树:

X
|_ setup.py
|_ X
   |_ someFile.py
   |_ __init__.py (empty)
   |_ Y
      |_ __init__.py (empty)
      |_ anotherFile.py

在 运行 宁 pip install -e . 之后,我可以 运行 在我系统的任何地方执行以下命令:

import X
from X import someFile
from X.Y import anotherFile

但是我不能运行:

from X import Y
Y.anotherFile

-> Module X.Y has no attribute "anotherFile".

我可以通过用 from X.Y import anotherFile 填充较低级别的 __init__.py 来解决这个问题,但这似乎有点奇怪。

这是为什么?我对 python 包的理解有误吗?

免责声明:之前可能有人问过这个问题,但这个问题太笼统了,我很难找到正确的 post。

其实很简单。对于 from X import Y,导入的模块是目录 Y 中的 __init__.py 文件,而不是所有其他文件。

但我认为真正的问题是,为什么?

假设 anotherFile 是您唯一需要的模块,因此您通过 from X.Y import anotherFile 导入 anotherFile。但实际上你还导入了 XY。虽然你不能通过 XY 访问它们,但是如果你 import syssys.modules.keys(),你可以看到这些模块为 XX.Y .并且可以通过sys.modules["X.Y"].a # suppose there is访问Y中的属性。也就是说Y目录下的__init__.py文件已经执行完毕

OK,那么现在如果导入 YX 也将执行该包下的所有文件,你猜怎么着?是的,即使您只需要 anotherFile 模块,也会执行目录 X 下的目录 Y 中的所有文件。而且这些文件还导入其他文件等等... 只需导入一次,整个项目就被导入了。