We can simply use:
crc = struct.unpack('>i', data)
why do people write it like this:
(crc,) = struct.unpack('>i', data)
What does the comma mean?
The first variant returns a single-element tuple:
In [13]: crc = struct.unpack('>i', '0000')
In [14]: crc
Out[14]: (808464432,)
To get to the value, you have to write crc[0]
.
The second variant unpacks the tuple, enabling you to write crc
instead of crc[0]
:
In [15]: (crc,) = struct.unpack('>i', '0000')
In [16]: crc
Out[16]: 808464432
the unpack
method returns a tuple of values. With the syntax you describe one can directly load the first value of the tuple into the variable crc
while the first example has a reference to the whole tuple and you would have to access the first value by writing crc[1]
later in the script.
So basically if you only want to use one of the return values you can use this method to directly load it in one variable.
The comma indicates crc
is part of a tuple. (Interestingly, it is the comma(s), not the parentheses, that indicate tuples in Python.) (crc,)
is a tuple with one element.
crc = struct.unpack('>i', data)
makes crc
a tuple.
(crc,) = struct.unpack('>i', data)
assigns crc
to the value of the first (and only) element in the tuple.