What's the python __all__ module level variable for?
我在python/lib源代码中见过很多这样的代码,但我不知道它是用来做什么的。
我以为它是用来限制模块中可访问的成员的。因此,当
我做了一个小例子,发现它没有如我所预期的那样起作用。
所以…python
它有两个目的:
任何读取源代码的人都会知道公开的公共API是什么。它并没有阻止他们在私人声明中到处乱翻,但确实提供了一个很好的警告,不要这样做。
使用
http://docs.python.org/tutorial/modules.html从-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.
它控制着当你
1 | from blah import * |
请参见从包导入*。