访问另一个模块的__all__

时间:2015-04-07 14:07:30

标签: python

我正在编写一个Python模块,在我的一个文件中,__all__有一个相当复杂的表达式:

# foo.py
__all__ = [ ... ]

在我希望用户使用的顶级模块中,我希望公开所有这些以及其他一些内容。我是否只是明确引用__all__

# the_module.py
import foo

__all__ = foo.__all__ + [ ... ]

或是否有某种方法可以使用:

from foo import *

__all__ = ???

2 个答案:

答案 0 :(得分:1)

你可以尝试一下:

# foo.py
__all__ = [1,2,3]    

然后

# bar.py
import foo
print foo.__all__

输出:

>>> python bar.py
[1, 2, 3]

或者,如果您想直接导入__all__

# bar.py
from foo import __all__
print __all__

输出:

>>> python bar.py
[1, 2, 3]

Python非常友好,只是为了它。

如果您想使用from module import *表单:

# foo.py
__all__ = [1,2,3]
__other_thing__ = [4,5,6]

然后

# bar.py
from foo import *
print foo.__all__
print foo.__other_thing__

输出:

>>> python bar.py
[1, 2, 3]
[4, 5, 6]

答案 1 :(得分:1)

请注意,__all__用于限制将从给定模块导入的名称。如果the_module.py中的任何内容

from foo import *会引入foo.__main__中定义的所有内容,因此import the_module的用户将能够直接访问the_module.py中定义的所有名称和任何内容。