在Python模块中,__all__
是一个特殊变量,它用于定义模块的公共接口。如果模块包含__all__
列表,那么只有在这个列表中的名称会被从模块中导入。当使用from module import *
语法时,__all__
变量可以控制哪些名称会被导入。
1. 示例
假设有一个名为example.py
的模块,其中定义了几个函数和变量:
# example.py
__all__ = ['public_function1', 'public_function2']
def public_function1():
pass
def public_function2():
pass
def private_function():
pass
some_variable = 42
在这个例子中,__all__
列表只包含public_function1
和public_function2
。这意味着如果使用from example import *
,只有这两个函数会被导入。
2. 使用__all__
# main.py
from example import *
public_function1() # 可访问
public_function2() # 可访问
private_function() # NameError: name 'private_function' is not defined
print(some_variable) # NameError: name 'some_variable' is not defined
由于private_function
和some_variable
不在__all__
列表中,它们不会被导入。
3. 没有__all__
的情况
如果模块中没有定义__all__
,那么from module import *
将导入所有不以下划线开头的名称:
# example.py
def public_function1():
pass
def public_function2():
pass
def _private_function():
pass
some_variable = 42
# main.py
from example import *
public_function1() # 可访问
public_function2() # 可访问
_private_function() # NameError: name '_private_function' is not defined
print(some_variable) # 可访问
在这种情况下,_private_function
因为以下划线开头,不会被导入,而其他名称都会被导入。
4. 空的__all__
如果__all__
是一个空列表,例如__all__ = []
,则意味着from module import *
不会导入模块中的任何名称:
# example.py
__all__ = []
def public_function1():
pass
def public_function2():
pass
some_variable = 42
# main.py
from example import *
public_function1() # NameError: name 'public_function1' is not defined
public_function2() # NameError: name 'public_function2' is not defined
print(some_variable) # NameError: name 'some_variable' is not defined
总结
__all__
的主要作用是控制from module import *
语句导入的名称列表。通过定义__all__
,可以明确模块的公共接口,隐藏实现细节,避免命名冲突。如果__all__
为空,则不会导入任何名称。