Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does var,_ = something mean in Python? String concatenation?

I am learning Python and am reading through an example script that includes some variable definitions that look like:

output,_ = call_command('git status')
output,_ = call_command('pwd')

def call_command(command):
    process = subprocess.Popen(command.split(' '),
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    return process.communicate()

If I print output I get the resulting shell output strung together, so I know it's concatenating the variables. But I can't find any reference to the ,_ convention in any of the docs. Can someone explain it to me so that I know for sure I am using it correctly?

like image 675
bryan kennedy Avatar asked Jan 30 '12 20:01

bryan kennedy


4 Answers

The general form

a, b = x, y

is tuple assignment. The corresponding parts are assigned, so the above is equivalent to:

a = x
b = y

In your case, call_command() returns a tuple of two elements (which is what process.communicate() returns). You're assigning the first one to output and the second one to _ (which is actually a variable name, typically used to name something when you don't care about the value).

like image 184
Greg Hewgill Avatar answered Nov 11 '22 12:11

Greg Hewgill


There are two conventions here:

  • Unpack results into a tuple of two elements (,)
  • I don't care about the second element of the tuple so use _ as the name of that variable.

In this particular case, process.communicate returns (stdout, stderr), but the code that calls call_command isn't interested in stderr so it uses this notation to get stdout directly. This would be more or less equivalent to:

result = call_command(<command>)
stdout = result[0]
like image 29
jcollado Avatar answered Nov 11 '22 13:11

jcollado


_ is a valid variable name in Python that is typically used when you're not intending to use a result for anything. So you're unpacking the results of the git commands into two variables named output and _, but will not use the second (I assume it is exit status or maybe standard error output).

like image 3
kindall Avatar answered Nov 11 '22 11:11

kindall


You see this in perl, too, with undef instead of _.

($dev, $ino, undef, undef, $uid, $gid) = stat($file);

See http://perldoc.perl.org/perldata.html#List-value-constructors

like image 2
tantalor Avatar answered Nov 11 '22 12:11

tantalor