What is the purpose of the single underscore “_” variable in Python?

后端 未结 5 1657
后悔当初
后悔当初 2020-11-21 04:04

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

if tbh.bag:
   n = 0
   for _ in tbh.bag.atom_set():
      n += 1
5条回答
  •  不思量自难忘°
    2020-11-21 04:45

    _ has 5 main conventional uses in Python:

    1. To hold the result of the last executed expression(/statement) in an interactive interpreter session. This precedent was set by the standard CPython interpreter, and other interpreters have followed suit
    2. 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: label, has_label, _ = text.partition(':').
    3. 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: callback = lambda _: True
    4. The python linter recognizes the underscore as a purposefully unused variable (both use cases above). For example year,month,day = date() will raise a lint warning if the day variable is not used later on in the code, the fix if the day is truly not needed is to write year,month,_ = date(). Same with lambda functions, lambda arg: 1.0 is creating a function requiring one argument but not using it, that will be caught by lint, the fix is to write lambda _: 1.0. An unused variable is often hiding a bug/typo (set day but used dya the next line).
    5. For translation lookup in i18n (see the gettext documentation for example), as in code like raise forms.ValidationError(_("Please enter a correct username")).
        # the usage of underscore in translation comes from examples in the doc
        # that have been copy/pasted over decades, like this one:
        import gettext
        gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
        gettext.textdomain('myapplication')
        _ = gettext.gettext
        # ...
        print(_('This is a translatable string.'))
    

    2019 update: Added lambda. For a long time this answer only listed three use cases, but the lambda case came up often enough, as noted here, to be worth listing explicitly

    2020 update: Added lint. Surprised nobody has highlighted this because it's common to have lint checks enforced on CI, flagging unused variables and potentially failing the build with a hard error if strict.

    The latter "throwaway variable or parameter name" uses cases 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).

提交回复
热议问题