gpt4 book ai didi

python - 即使我在模块中使用下划线作为隐藏函数和变量的前缀,我是否应该定义 __all__?

转载 作者:行者123 更新时间:2023-11-28 20:23:32 28 4
gpt4 key购买 nike

从模块的外部用户的角度来看,两者都是必要的吗?

根据我的理解,通过在隐藏函数前正确加上下划线前缀,它基本上与显式定义 __all__ 做同样的事情,但我一直看到开发人员在他们的代码中同时做这两种事情。这是为什么?

最佳答案

当使用 from modulename import * 从模块导入时,以下划线开头的名称确实会被跳过。

但是,模块很少 包含公共(public) API 对象。通常您也进行了导入以支持代码,并且那些 名称在模块中也是全局的。如果没有 __all__,这些名称也将成为导入的一部分。

换句话说,除非您想在下面的示例中“导出”os,否则您应该使用__all__:

import os
from .implementation import some_other_api_call

_module_path = os.path.dirname(os.path.abspath(__file__))
_template = open(os.path.join(_module_path, 'templates/foo_template.txt')).read()

VERSION = '1.0.0'

def make_bar(baz, ham, spam):
return _template.format(baz, ham, spam)

__all__ = ['some_other_api_call', 'make_bar']

因为没有 __all__ 列表,Python 无法在此处区分 some_other_api_callos 并判断在使用 时不应导入哪个>从 ... 导入 *

您可以通过重命名所有导入来解决此问题,因此 import os as _os,但这只会降低您的代码的可读性。

明确的导出列表总是很好。正如 Python 之禅告诉您的那样,显式优于隐式。

关于python - 即使我在模块中使用下划线作为隐藏函数和变量的前缀,我是否应该定义 __all__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20334880/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com