gpt4 book ai didi

python - 为什么 python 导入重命名为前导下划线

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

我在使用 functools.partial 以及 python 源代码本身时注意到它。例如。下面来自 collections.py

from operator import itemgetter as _itemgetter, eq as _eq
from keyword import iskeyword as _iskeyword
import sys as _sys
import heapq as _heapq

这样做的理由是什么?如果这是 C++,我知道它可能会导致命名空间冲突,但是在 python 中,这些名称不会是导入它们的模块的本地名称吗?除非有人确实导入 *,但不鼓励这样做,所以我不确定这就是原因。

最佳答案

这表示函数、变量或类是私有(private)的。它不仅是人类的约定(所以你应该知道不要使用它),而且 python 还强制在某些情况下不会导入它。

来自 PEP8 :

_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

PS:使用 import * 不是好的做法,但那是另一个讨论。

关于python - 为什么 python 导入重命名为前导下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47138594/

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