'_' and '__'

Cameron Simpson cs at cskk.id.au
Sat May 26 20:14:49 EDT 2018


On 27May2018 09:46, Chris Angelico <rosuav at gmail.com> wrote:
>On Sun, May 27, 2018 at 9:40 AM, Thomas Jollans <tjol at tjol.eu> wrote:
>> There's nothing special about _, it's just a possible name of a
>> variable, albeit a very short and entirely uninformative one. Normally,
>> it's not something you'd actually want to name a variable, of course.
>>
>> As such, _ has become an idiomatic name for dummy variables, i.e.
>> something you use when syntax requires you to give a variable name, but
>> you don't actually want one (probably because you're throwing the
>> variable away). This mostly happens in generator expressions/list
>> comprehensions.
>
>Yes, and also in stand-alone 'for' loops where you don't care about
>the iteration variable:
>
>for _ in range(3): datafile.skipline()
>
>The only actual significance of this name is that the interactive
>interpreter will stash the result of the previous expression in that
>variable.
>
>>>> 6 * 7
>42
>>>> _ + 1
>43
>
>Other than that, it is simply an ordinary name, but one that has some
>conventions attached to it.

Also, various lint tools know that the name "_" is used in this way, and don't 
complain that a variable is assigned to and not used if its name is "_".

Cheers,
Cameron Simpson <cs at cskk.id.au>



More information about the Python-list mailing list