关于命名空间:什么是python __all__模块级变量?

What's the python __all__ module level variable for?

本问题已经有最佳答案,请猛点这里访问。

我在python/lib源代码中见过很多这样的代码,但我不知道它是用来做什么的。

我以为它是用来限制模块中可访问的成员的。因此,当dir(module)时,只有__all__处的元素才会出现。

我做了一个小例子,发现它没有如我所预期的那样起作用。

所以…python __all__模块级变量的作用是什么?


它有两个目的:

  • 任何读取源代码的人都会知道公开的公共API是什么。它并没有阻止他们在私人声明中到处乱翻,但确实提供了一个很好的警告,不要这样做。

  • 使用from mod import *时,只导入__all__中列出的名称。在我看来,这并不重要,因为进口所有的东西是一个非常坏的主意。


  • 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 when from 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 *

    请参见从包导入*。