python __all__ 模块级变量有什么用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2187583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the python __all__ module level variable for?
提问by Juanjo Conti
I've seen it a lot in python/Lib source code but I don't know what it is for.
我在 python/Lib 源代码中看到了很多,但我不知道它是做什么用的。
I thought it was used to limit accessible members of of a module. So only the elements at __all__
will show up when dir(module)
.
我认为它用于限制模块的可访问成员。所以只有 at 元素__all__
会在 时出现dir(module)
。
I did a little example and saw it was not working as I expected.
我做了一个小例子,发现它没有按我预期的那样工作。
So... What's the python __all__
module level variable for?
那么... python__all__
模块级变量的用途是什么?
回答by John Millikin
It has two purposes:
它有两个目的:
Anybody who reads the source will know what the exposed public API is. It doesn't preventthem from poking around in private declarations, but does provide a good warning not to.
When using
from mod import *
, only names listed in__all__
will be imported. This is not as important, in my opinion, because importing everything is a reallybad idea.
任何阅读源代码的人都会知道公开的公共 API 是什么。它并不能阻止他们在私人声明中闲逛,但确实提供了一个很好的警告。
使用 时
from mod import *
,只会__all__
导入 中列出的名称。在我看来,这并不重要,因为导入所有内容是一个非常糟糕的主意。
回答by Jochen Ritzel
http://docs.python.org/tutorial/modules.html#importing-from-a-package
http://docs.python.org/tutorial/modules.html#importing-from-a-package
Now what happens when the user writes
from sound.effects import *
? Ideally, one would hope that this somehow goes out to the filesystem, finds which submodules are present in the package, and imports them all. This could take a long time and importing sub-modules might have unwanted side-effects that should only happen when the sub-module is explicitly imported.The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a package's
__init__.py
code defines a list named__all__
, it is taken to be the list of module names that should be imported whenfrom package import *
is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they don't see a use for importing * from their package.
现在当用户写入时会发生什么
from sound.effects import *
?理想情况下,人们希望这以某种方式进入文件系统,找到包中存在哪些子模块,并将它们全部导入。这可能需要很长时间,并且导入子模块可能会产生不需要的副作用,只有在显式导入子模块时才会发生这种情况。唯一的解决方案是让包作者提供包的显式索引。import 语句使用以下约定:如果包的
__init__.py
代码定义了一个名为 的列表__all__
,则它被认为from package import *
是遇到时应导入的模块名称列表。当软件包的新版本发布时,由软件包作者来保持这个列表是最新的。包作者也可能决定不支持它,如果他们没有看到从他们的包中导入 * 的用途。
回答by John La Rooy
It controls what you get pulled into your namepsace when you
它控制你在你的命名空间中被拉入的内容
from blah import *
See Importing * from a Package
请参阅从包中导入 *