16

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

doug
  • 65,292
  • 23
  • 156
  • 195
  • I use `_` (or an allowed language equivalent) to signify a "throw-away" value. –  Feb 01 '11 at 07:48

5 Answers5

33

I've seen it used in two ways. Both as a throw-away variable but more commonly as a text wrapper for internationalization.

Throw-away variable

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.

i18n wrapper

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.

Lennart Regebro
  • 147,792
  • 40
  • 207
  • 241
  • +1 for recommending against the use of `_` as an anonymous variable. It tends to confuse people, and it clashes with `_` in the interactive interpreter. – Sven Marnach Feb 01 '11 at 10:30
  • In spite of your recommendations, the use of `_` for ignored values has become pretty idiomatic Python, to the point where it has been [codified as a special case in PEP 634](https://www.python.org/dev/peps/pep-0634/#id3). – user3840170 Mar 31 '21 at 19:30
7

_ is a somewhat special variable name. In the shell, it contains the value of the previously evaluated expression:

>>> 1+2
3
>>> _+4
7

Within scripts, it's commonly used as a throwaway variable, i. e. one that's needed for semantical reasons but that isn't going to be used later. Syntactically, it's just a variable like any other.

Tim Pietzcker
  • 297,146
  • 54
  • 452
  • 522
7

The advantages are that it's a single character and it's "nameless".

The disadvantage is that it's frequently used for I18N, as a reference to gettext.gettext().

Ignacio Vazquez-Abrams
  • 699,552
  • 132
  • 1,235
  • 1,283
3

I've seen the variable _ used when you don't care about what value it will get, more or less like a /dev/null variable.

In python philosophy readability is much more valued than in other languages, and for example:

x, y, _, w = getPoint()

is compact and more readable than other alternatives, showing that you don't care about the z coordinate of the result. Other uses could be

for _ in xrange(10):
    print "Hello, world."

or

def matrix(rows, columns):
    return [[0] * columns for _ in xrange(rows)]

For the language indeed _ is a valid identifier as any other one even if in some interactive python loops it has a special meaning.

This use as an "anonymous variable" is not very frequent but still there so you may find it in existing code. For example PyChecker will not report anything about the matrix function above but it will complain if you use a "normal" variable name.

There are also packages that however give to _ a well defined meaning (gettext).

6502
  • 104,192
  • 14
  • 145
  • 251
  • 1
    If anyone's wondering, using '_' as a throwaway variable that static analyzers don't complain about (PyLint also ignores unused underscore variables) stems from other languages that have this as a language specification. The earliest example I know of is Prolog, a language which labels unused variables as errors. – Carrotman42 Apr 12 '13 at 15:23
-2

There is not a good reason to use _ in the scripts. While using from interactive interpretor if you are doing any mathematical calculation, and you want the the result of the previous expression, you can use _. Python tutorial introduces the _ in the very same context. I see that the behavior is carried over from certain shell behaviors.

In your example:

_, x = L.pop()

would fail because L.pop() would return a single value and you cannot assign it to two variables and also it not a good idea to assign values to _ which has a special meaning.

Senthil Kumaran
  • 47,625
  • 13
  • 83
  • 117