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?
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).
There are two conventions here:
,
)_
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]
_
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With