Unveiling the Role of "__all__" in Python
The "__all__" list in an "__init__.py" file plays a critical role in controlling what symbols are exported when "from
Specifically, "__all__" defines a list of strings that represent the symbols in the module that will be accessible when the "import *" wildcard syntax is employed. For instance, consider the following code in a module named "foo.py":
__all__ = ['bar', 'baz'] waz = 5 bar = 10 def baz(): return 'baz'
In this example, the symbols "bar" and "baz" are explicitly exported using "__all__". As a result, when you import the "foo" module with "from foo import *", only these two symbols will be available. All other symbols, such as "waz," will be hidden.
from foo import * print(bar) print(baz()) # Attempting to access "waz" will raise an exception. print(waz)
If the "__all__" list is commented out, the default import behavior takes effect, where all symbols that do not begin with an underscore are imported. In this case, the import statement would succeed, and "waz" would also be accessible.
# Comment out __all__ from foo import * print(bar) print(baz()) print(waz)
It's important to note that "__all__" only affects the "from
The above is the detailed content of How Does Python's `__all__` Control Module Imports with `from import *`?. For more information, please follow other related articles on the PHP Chinese website!