使用闭包代替 __all__
来限制 Python 模块暴露的名称是一个好主意吗?这可以防止程序员意外使用模块的错误名称(import urllib; urllib.os.getlogin()
),以及避免 "from x import *
" 的命名空间污染。
def _init_module():
global foo
import bar
def foo():
return bar.baz.operation()
class Quux(bar.baz.Splort): pass
_init_module(); del _init_module
使用__all__
与相同模块的比较:
__all__ = ['foo']
import bar
def foo():
return bar.baz.operation()
class Quux(bar.baz.Splort): pass
为了避免污染模块名称空间,函数可以采用这种风格:
def foo():
import bar
bar.baz.operation()
这可能对于一个希望帮助用户在交互式内省期间区分其API和包使用的其他模块API的大型包非常有用。另一方面,也许IPython应该在选项完成期间简单地区分
__all__
中的名称,并且更多的用户应该使用允许他们跳转到文件以查看每个名称定义的IDE。
__all__
来定义相同的模块。 - joeforkerimport foo as bar
,那么他们得到的名称是bar
,如果他们使用import foo
,则得到的名称是foo
。闭包有什么不同之处? - stevehafrom zope.app.intid.interfaces import IIntIds
,那么你会破坏他们的模块。当从IPython shell内省API时,很难知道任何特定的模块级名称是接口还是实现。 - joeforker