Why does unpacking a structure lead to a tuple?

After packing the whole into a Python structure, unpacking results in a set, even if it contains only one element. Why does unpacking return a tuple?

>>> x = struct.pack(">i",1) >>> str(x) '\x00\x00\x00\x01' >>> y = struct.unpack(">i",x) >>> y (1,) 
+5
source share
2 answers

Please view the struct doc document first

struct.pack (fmt, v1, v2, ...)

Returns a string containing the values ​​v1, v2, ... packed in accordance with this format. The arguments must exactly match the values ​​needed for the format.

-

struct.unpack (fmt, string)

Unpack the string (supposedly packaged pack (fmt, ...)) in accordance with this format. The result is a tuple even if it contains exactly one element. The string must contain exactly the amount of data required by the format (len (string) must equal calcsize (FMT)).

Because struct.pack defined as struct.pack(fmt, v1, v2, ...) . It takes a list of arguments without a keyword ( v1, v2, ... , aka *args ), so struct.unpack needs to return the list as an object, therefore a tuple.

It would be easy to see if you consider the package as

 x = struct.pack(fmt, *args) args = struct.unpack(fmt, x) # return *args 

Example:

 >>> x = struct.pack(">i", 1) >>> struct.unpack(">i", x) (1,) >>> x = struct.pack(">iii", 1, 2, 3) >>> struct.unpack(">iii", x) (1, 2, 3) 
+5
source

Think of a use-case that loads binary data written using C. Python cannot distinguish if binary data was written using a structure or using a single whole. So, I think it makes sense that it always makes sense to return a tuple, since struct pack and unpack perform conversions between Python and C structs.

+1
source

All Articles