15

For example, I read a code:

def parse_doc(self, _, doc):

What does the underline "_" mean?

Serenity
  • 35,289
  • 20
  • 120
  • 115
xueliang liu
  • 556
  • 3
  • 13

3 Answers3

45

It usually is a place holder for a variable we don't care about. For instance if you have a for-loop and you don't care about the value of the index, you can do something like

for _ in xrange(10):
   print "hello World." # just want the message 10 times, no need for index val

another example, if a function returns a tuple and you don't care about one of the values you could use _ to make this explicit. E.g.,

val, _ = funky_func() # "ignore" one of the return values

Aside

Unrelated to the use of '_' in OP's question, but still neat/useful. In the Python shell, '_' will contain the result of the last operation. E.g.,

>>> 55+4
59
>>> _
59
>>> 3 * _
177
>>>
Levon
  • 138,105
  • 33
  • 200
  • 191
  • _("sometext") usually indicates text to be translated (again unrelated to OP's Q) – Joran Beasley Jul 10 '12 at 21:44
  • @xueliangliu If this answered your question about the meaning of `'_'` please consider [accepting this answer by clicking the checkmark](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) next to the answer. It will reward both of us with some rep points and mark this problem as solved. – Levon Jul 12 '12 at 17:13
6

Like doc it's a variable name. Usually naming a variable _ indicates that it won't be used.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • or _("something") indicates text to be localized(translated) ... its also a magic variable that holds the last result when used in the python shell ... – Joran Beasley Jul 10 '12 at 21:43
4

_ is a valid variable name in python. But it is mostly used in i18n, so it's better to not to use it for other purposes.

Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504