单下划线“_”的用途是什么? Python 中的变量?
这段代码中for
后面的_
是什么意思?
if tbh.bag:
n = 0
for _ in tbh.bag.atom_set():
n += 1
What is the meaning of _
after for
in this code?
if tbh.bag:
n = 0
for _ in tbh.bag.atom_set():
n += 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
_
在 Python 中有 3 个主要的常规用途:在交互式中保存最后执行的表达式的结果
解释器会话(请参阅文档)。这个先例是由标准 CPython 开创的
口译员,其他口译员也纷纷效仿
对于 i18n 中的翻译查找(请参阅
gettext
例如文档),如代码所示
作为通用“一次性”变量名称:
表示该部分
函数结果的值被故意忽略(从概念上讲,它被丢弃。),如代码所示:
作为函数定义的一部分(使用
def
或lambda
),其中签名是固定的(例如通过回调或父类 API),但是
这个特定的函数实现不需要所有的
参数,如代码所示:
[很长一段时间以来,这个答案都没有列出这个用例,但它经常出现,正如所指出的此处的目的值得明确列出。]
此用例可能与翻译查找用例冲突,因此有必要避免在任何也将其用于 i18n 翻译的代码块中使用
_
作为一次性变量(许多人更喜欢使用双下划线,__
,作为他们的一次性变量正是这个原因)。Linter 经常认识到这种用例。例如,如果稍后在代码中未使用
day
,year、month、day = date()
将引发 lint 警告。如果确实不需要day
,则修复方法是编写year, Month, _ = date()
。与 lambda 函数相同,lambda arg: 1.0
创建一个需要一个参数但不使用它的函数,该函数将被 lint 捕获。修复方法是编写lambda _: 1.0
。未使用的变量通常会隐藏错误/拼写错误(例如设置day
但在下一行中使用dya
)。Python 3.10 中添加的模式匹配功能将这种用法从“约定”提升为“语言语法”,其中涉及
match
语句:在匹配情况下,_
是通配符模式,运行时甚至不绑定值到符号这种情况。对于其他用例,请记住
_
仍然是有效的变量名称,因此仍然会使对象保持活动状态。如果这是不可取的(例如释放内存或外部资源),显式的del name
调用将满足 linter 正在使用该名称的要求,并立即清除引用到对象。_
has 3 main conventional uses in Python:To hold the result of the last executed expression in an interactive
interpreter session (see docs). This precedent was set by the standard CPython
interpreter, and other interpreters have followed suit
For translation lookup in i18n (see the
gettext
documentation for example), as in code like
As a general purpose "throwaway" variable name:
To indicate that part
of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like:
As part of a function definition (using either
def
orlambda
), wherethe signature is fixed (e.g. by a callback or parent class API), but
this particular function implementation doesn't need all of the
parameters, as in code like:
[For a long time this answer didn't list this use case, but it came up often enough, as noted here, to be worth listing explicitly.]
This use case can conflict with the translation lookup use case, so it is necessary to avoid using
_
as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore,__
, as their throwaway variable for exactly this reason).Linters often recognize this use case. For example
year, month, day = date()
will raise a lint warning ifday
is not used later in the code. The fix, ifday
is truly not needed, is to writeyear, month, _ = date()
. Same with lambda functions,lambda arg: 1.0
creates a function requiring one argument but not using it, which will be caught by lint. The fix is to writelambda _: 1.0
. An unused variable is often hiding a bug/typo (e.g. setday
but usedya
in the next line).The pattern matching feature added in Python 3.10 elevated this usage from "convention" to "language syntax" where
match
statements are concerned: in match cases,_
is a wildcard pattern, and the runtime doesn't even bind a value to the symbol in that case.For other use cases, remember that
_
is still a valid variable name, and hence will still keep objects alive. In cases where this is undesirable (e.g. to release memory or external resources) an explicitdel name
call will both satisfy linters that the name is being used, and promptly clear the reference to the object.它只是一个变量名,Python 中通常使用
_
来表示一次性变量。它只是表明循环变量实际上没有被使用。It's just a variable name, and it's conventional in python to use
_
for throwaway variables. It just indicates that the loop variable isn't actually used.下划线
_
在Python中被视为“我不在乎”或“一次性”变量Python解释器存储最后一个表达式名为
_
的特殊变量的值。<前><代码>>>> 10
10
>>>>> _
10
>>>>> _ * 3
30
下划线
_
也用于忽略特定值。如果您不需要特定值或未使用这些值,只需将值分配给下划线即可。解压时忽略一个值
<前><代码>x, _, y = (1, 2, 3)
>>>>> x
1
>>>>> y
3
忽略索引
Underscore
_
is considered as "I don't care" or "throwaway" variable in PythonThe python interpreter stores the last expression value to the special variable called
_
.The underscore
_
is also used for ignoring the specific values. If you don’t need the specific values or the values are not used, just assign the values to underscore.Ignore a value when unpacking
Ignore the index
Python中使用下划线有5种情况。
用于存储解释器中最后一个表达式的值。
用于忽略特定值。 (所谓“我不在乎”)
为变量或函数的名称赋予特殊的含义和功能。
用作“国际化 (i18n)”或“本地化 (l10n)”功能。
分隔数字文字值的数字。
这里是一篇很好的文章,其中包含 mingrammer。
There are 5 cases for using the underscore in Python.
For storing the value of last expression in interpreter.
For ignoring the specific values. (so-called “I don’t care”)
To give special meanings and functions to name of variables or functions.
To use as ‘internationalization (i18n)’ or ‘localization (l10n)’ functions.
To separate the digits of number literal value.
Here is a nice article with examples by mingrammer.
对于Python语言来说,
_
一般没有特殊含义。它是一个有效的标识符,就像_foo
、foo_
或_f_o_o_
。唯一的例外是 Python 3.10 以来的
match
语句:否则,
_
纯粹是按照惯例。有几种常见情况:当不打算使用变量但语法/语义需要名称时,使用虚拟名称。
许多 REPL/shell 将最后一个顶级表达式的结果存储到
builtins._
。<块引用>
特殊标识符
_
用于交互式解释器中,用于存储上次求值的结果;它存储在builtins
模块中。当不处于交互模式时,_
没有特殊含义并且未定义。 [来源]由于名称的查找方式,除非被全局或本地
_
定义遮蔽,否则裸露的_
引用builtins._
.<前><代码>>>> 42
42
>>>>> f'最后一个答案是{_}'
“最后的答案是 42”
>>>>> _
“最后的答案是 42”
>>>>> _ = 4 # 带有全局 ``_`` 的影子``builtins._``
>>>>> 23
23
>>>>> _
4
注意:某些 shell(例如
ipython
)不会分配给builtins._
,而是分配特殊情况的_
.在国际化和本地化上下文中,
_
用作主要翻译功能的别名。<块引用>
gettext.gettext(消息)
根据当前全局域、语言和区域设置目录返回消息的本地化翻译。此函数在本地命名空间中通常别名为
_()
(请参阅下面的示例)。As far as the Python languages is concerned,
_
generally has no special meaning. It is a valid identifier just like_foo
,foo_
or_f_o_o_
.The only exception are
match
statements since Python 3.10:Otherwise, any special meaning of
_
is purely by convention. Several cases are common:A dummy name when a variable is not intended to be used, but a name is required by syntax/semantics.
Many REPLs/shells store the result of the last top-level expression to
builtins._
.Due to the way names are looked up, unless shadowed by a global or local
_
definition the bare_
refers tobuiltins._
.Note: Some shells such as
ipython
do not assign tobuiltins._
but special-case_
.In the context internationalization and localization,
_
is used as an alias for the primary translation function.