I have seen this in a few contexts, e.g.,
in sequence unpacking:
_, x = L.pop() # e.g., L is a list of tuples
to initialize a container:
X = _
So obviously this is not an element of the formal python syntax, rather the uses i am aware of appear discretionary.
So I'm curious what is the likely reason for its use and what are the advantages generally (if any)?
Note: my question relates to the use of "_" in scripts, modules, etc., but not its use at the interactive prompt. In IDLE, the interactive interpreter packaged with python, as well as in ipython, "_", is used as a placeholder for most recently returned result).
I've seen it used in two ways. Both as a throw-away variable but more commonly as a text wrapper for internationalization.
name, _ = 'bida.bombu.foo'.split('.', 1)
Although I would not recommend this. Call it "ignored" instead.
name, ignored = 'bida.bombu.foo'.split('.', 1)
It's clearer.
from zope.i18nmessageid import MessageFactory
_ = MessageFactory('my.domain')
label = _("The label text")
label
will here be a "Message", an object that has a message id and a domain, and when rendered to a user interface (like a web page) it will be translated to the current user language via a message catalog, so that the label will end up in the local language of the user.
_
is used here because it is short and unobtrusive. The resulting code, _("The label text")
doesn't look to different from just a string, while MyDomainMessage("The label text")
does look very different and also is much longer.