单下划线“_"的目的是什么?Python中的变量? [英] What is the purpose of the single underscore "_" variable in Python?

查看:24
本文介绍了单下划线“_"的目的是什么?Python中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码中for后面的_是什么意思?

What is the meaning of _ after for in this code?

if tbh.bag:
    n = 0
    for _ in tbh.bag.atom_set():
        n += 1

推荐答案

_ 在 Python 中有 3 个主要的常规用途:

_ has 3 main conventional uses in Python:

  1. 在交互式中保存上次执行的表达式的结果解释器会话(参见 docs).这个先例是由标准 CPython 设定的口译员,其他口译员也纷纷效仿

  1. 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

对于 i18n 中的翻译查找(请参阅gettext文档例如),如在代码中

For translation lookup in i18n (see the gettext documentation for example), as in code like

raise forms.ValidationError(_("Please enter a correct username"))

  • 作为通用的一次性"变量名:

  • As a general purpose "throwaway" variable name:

    1. 表示该部分一个函数结果被故意忽略(从概念上讲,它被丢弃.),如在代码中:

    1. To indicate that part of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like:

    label, has_label, _ = text.partition(':')
    

  • 作为函数定义的一部分(使用 deflambda),其中签名是固定的(例如通过回调或父类 API),但是这个特定的函数实现不需要所有的参数,如代码:

  • As part of a function definition (using either def or lambda), where the 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:

    def callback(_):
        return True
    

    [很长一段时间这个答案没有列出这个用例,但它经常出现,正如所指出的此处,值得明确列出.]

    [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.]

    此用例可能与翻译查找用例发生冲突,因此有必要避免将 _ 用作任何代码块中的一次性变量,这些变量也将其用于 i18n 翻译(许多人更喜欢使用双下划线,__,正是出于这个原因,作为他们的一次性变量).

    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).

    Linter 经常识别这个用例.例如,如果 day 后面没有在代码中使用,year, month, day = date() 将引发 lint 警告.如果确实不需要 day,则修复方法是编写 year, month, _ = date().与 lambda 函数相同,lambda arg: 1.0 创建一个需要一个参数但不使用它的函数,该函数将被 lint 捕获.修复方法是编写 lambda _: 1.0.未使用的变量通常会隐藏错误/错别字(例如设置 day 但在下一行使用 dya).

    Linters often recognize this use case. For example year, month, day = date() will raise a lint warning if day is not used later in the code. The fix, if day is truly not needed, is to write year, 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 write lambda _: 1.0. An unused variable is often hiding a bug/typo (e.g. set day but use dya in the next line).

    Python 3.10 中添加的模式匹配功能将这种用法从约定"提升到了到语言语法"其中涉及 match 语句:在匹配情况下,_通配符模式,在这种情况下,运行时甚至不会将值绑定到符号.

    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.

    对于其他用例,请记住 _ 仍然是一个有效的变量名,因此仍然会使对象保持活动状态.如果这是不合需要的(例如释放内存或外部资源),显式的 del name 调用将满足 linter 正在使用的名称,立即清除引用对象.

    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 explicit del name call will both satisfy linters that the name is being used, and promptly clear the reference to the object.

    这篇关于单下划线“_"的目的是什么?Python中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆