What is the meaning of _
after for
in this code?
if tbh.bag:
n = 0
for _ in tbh.bag.atom_set():
n += 1
_
has 5 main conventional uses in Python:
label, has_label, _ = text.partition(':')
.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
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).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).