问题描述
命名空间Python包(没有__init__.py
)和常规Python包(具有__init__.py
)之间有什么区别,特别是当常规包的__init__.py
为空时?
What's the difference between a namespace Python package (no __init__.py
) and a regular Python package (has an __init__.py
), especially when __init__.py
is empty for a regular package?
我很好奇,因为最近我一直忘记在自己制作的软件包中制作__init__.py
,而且我从没发现任何问题.实际上,它们的行为似乎与常规软件包相同.
I am curious because recently I've been forgetting to make __init__.py
in packages I make, and I never noticed any problems. In fact, they seem to behave identically to regular packages.
仅Python 3.3支持命名空间软件包(请参阅PEP 420 ),因此,这个问题自然仅适用于Python 3.
Namespace packages only supported from Python 3.3 (see PEP 420), so naturally, this question only applies to Python 3.
推荐答案
阅读链接和 PEP420 命名空间软件包和常规软件包之间的明显区别是,常规软件包可能包含__init__.py
中的各种初始化代码,这是命名空间软件包是一个虚拟软件包,其内容可以沿Python的查找路径分布在各个位置.
Reading link from Aaron, and PEP420, it appears that the fundamental difference between a namespace package and a regular package, beside the obvious difference that a regular package may contain various initialization code in __init__.py
, is that a namespace package is a virtual package whose contents can be distributed in various places along Python's lookup path.
例如,给定
a/foo/bar.py
b/foo/baz.py
如果b
和a
都在Python的路径中,则可以自由导入foo.bar
和foo.baz
.
If both b
and a
are in Python's path, you can import foo.bar
and foo.baz
freely.
当然,这引出了一个问题,如果不需要__init__.py
,那么在其他所有条件都相等的情况下,制作常规包或名称空间包会更好,但是有点不合时宜.
Of course, this begs the question that, if __init__.py
is not needed, then all other things being equal, is it better to make a regular package or a namespace package, but is a little off-topic.
这篇关于命名空间与常规包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!