In python, what the underline parameter mean in function

前端 未结 3 1265
长发绾君心
长发绾君心 2020-12-30 05:12

For example, I read a code:

def parse_doc(self, _, doc):

What does the underline \"_\" mean?

相关标签:
3条回答
  • 2020-12-30 05:41

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

    0 讨论(0)
  • 2020-12-30 05:52

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

    0 讨论(0)
  • 2020-12-30 06:01

    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
    >>>
    
    0 讨论(0)
提交回复
热议问题