Python __all__用法


Python all用法

简单的说,Python all的作用就是约定from package import *的行为,比如有个模块:
foo.py定义如下:

1
2
3
4
5
6
7
8
9
10
11
import os
__all__ = ['name','othername']
name = 'foo'
othername = 'bar'
def fun():
return dir(os)

此时,使用

1
from foo import *

导入所有对象时候,只能导入name和othername,无法导入其他的对象:
1
2
3
4
5
6
7
8
9
10
11
12
>>> from foo import *
>>> os
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>> fun
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'fun' is not defined
>>> name,othername
('foo', 'bar')