Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,)
like image 244
Jedi Avatar asked Jul 11 '16 01:07

Jedi


1 Answers

Think of a use case that loads binary data written using C language. Python won't be able to differentiate if binary data was written using a struct or using a single integer. So, I think, logically it makes sense to return tuple always, since struct pack and unpack perform conversions between Python values and C structs.

like image 199
Kevin Avatar answered Sep 28 '22 00:09

Kevin