Home > Backend Development > Python Tutorial > How Does Python's `__all__` Control Module Imports with `from import *`?

How Does Python's `__all__` Control Module Imports with `from import *`?

Patricia Arquette
Release: 2024-12-12 18:00:25
Original
841 people have browsed it

How Does Python's `__all__` Control Module Imports with `from  import *`?

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 import *" is used on that module.

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'
Copy after login

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)
Copy after login

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)
Copy after login

It's important to note that "__all__" only affects the "from import *" syntax. Members that are not mentioned in "__all__" can still be accessed from outside the module by using specific import statements, such as "from import ".

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template