If you look at Python source code or the relevant framework of the source code, always at the __init__.py beginning of the source file and see a definition of a __all__ variable, today to say its role. Orangleliu
Source of the problem
Can someone explain all in Python?
Problem
I am more and more using Python, often see the __all__ variables __init__.py in various files, who can explain why do it?
Answer
It is a list variable consisting of a string element that defines the from <module> import * symbols that can be exported when you import a module (this represents variables, functions, classes, and so on).
For example, the following code in foo.py , explicitly exported the symbol bar ,baz
__all__ = [‘bar‘‘baz‘510def baz():return‘baz‘
The import implementation is as follows:
from foo import *print barprint"waz"notmodule"waz"并没有从模块中导出,因为 __all__ 没有定义print waz
If the foo.py __all__ comment is dropped, then the code above does not have a problem, the import * default behavior is to export all the symbols from the given namespace (except for the private variables that begin with the underscore).
Attention
It is important to note that this import is only affected by the way it is imported and __all__ from <module> import * from <module> import <member> can still be imported from outside.
[Ask and Answer] What is the role of __all__ in Python?