我正在编写一个Python模块,在我的一个文件中,__all__
有一个相当复杂的表达式:
# foo.py
__all__ = [ ... ]
在我希望用户使用的顶级模块中,我希望公开所有这些以及其他一些内容。我是否只是明确引用__all__
?
# the_module.py
import foo
__all__ = foo.__all__ + [ ... ]
或是否有某种方法可以使用:
from foo import *
__all__ = ???
答案 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
中定义的所有名称和任何内容。