Python中__all__的使用

Python代码文件test.py如下

def _local_func():
    print 'local'


def test():
    _local_func()

如果执行from test import *,有哪些函数能被导出呢?

按照Python的规则,内部私有函数已_开头,因此将只有test函数能够调用。

>>> from test import *
>>> test()
local
>>> _local_func()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_local_func' is not defined
>>>

Python中并不存在接口可见性的控制,如果想强行调入私有函数,也是可以的,from test import _local_func。但可以通过__all__属性来控制import *的导出范围。

__all__ = ['test']


def _local_func():
    print 'local'


def test():
    _local_func()


def test1():
    _local_func()

执行结果如下

>>> from test import *
>>> test1()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'test1' is not defined
>>> test()
local
>>>

但是这种控制也仅仅限于import *这种情况。PEP8中规定了__all__需要位于import和函数之间