Search code examples
pythonstructtuplespackunpack

Why does unpacking a struct result in a tuple?


After packing an integer in a Python struct, the unpacking results in a tuple even if it contains only one item. Why does unpacking return a tuple?

>>> x = struct.pack(">i",1)

>>> str(x)
'\x00\x00\x00\x01'

>>> y = struct.unpack(">i",x)

>>> y
(1,)

Solution

  • Please see doc first struct doc

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

    Return a string containing the values v1, v2, ... packed according to the given format. The arguments must match the values required by the format exactly.

    --

    struct.unpack(fmt, string)

    Unpack the string (presumably packed by pack(fmt, ...)) according to the given format. The result is a tuple even if it contains exactly one item. The string must contain exactly the amount of data required by the format (len(string) must equal calcsize(fmt)).

    Because struct.pack is define as struct.pack(fmt, v1, v2, ...). It accept a non-keyworded argument list (v1, v2, ..., aka *args), so struct.unpack need return a list like object, that's why tuple.

    It would be easy to understand if you consider pack 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)