Section 12.38

struct module

Full name: struct: short for structure, after the struct type of the C programming language, which groups named fields into one record.

Definition

The struct module is the Python §12.23 standard-library module that converts Python values, such as integers and floating-point numbers §4.49, to and from bytes. A format string describes the layout. An optional first character sets the byte order §4.21 (which byte of a number comes first), the field sizes and the alignment §4.22 (whether padding bytes separate fields); each following character names one field’s type, such as H for a 2-byte unsigned integer. struct.pack turns values into bytes; struct.unpack reverses it. Without a first character, the layout follows the machine running Python.

The idea

A protocol specification says that a message header is a 1-byte version, then a 2-byte length, then a 4-byte sequence number, with every multi-byte field big-endian, most significant byte first. A Python integer has no fixed size and no byte order, so before it can be sent the program must decide exactly which bytes stand for it. struct.pack("!BHI", version, length, seq) makes that decision from a short format string, and struct.unpack reverses it on the receiving side.

A format string is a form for bytes. Each character is a box of fixed width, and the first character says in which direction multi-byte boxes are filled and whether gaps are left between boxes. A native form, @ or no first character, copies the habits of the machine running Python: its byte order, its C compiler’s sizes for types such as long, and the gaps that compiler leaves to align fields. Those habits suit data exchanged with C code on the same machine. A wire format, the exact byte layout of data sent between programs, is a contract between two machines whose habits may differ, so the format string alone must fix the layout; an explicit standard prefix does that.

How it works

The first character of the format string:

Standard sizes are fixed by the module and are the same on every machine; native sizes are those of the C compiler that built Python. “No alignment” means that no padding bytes are inserted.

The field codes, with their standard sizes: x is one padding byte, which takes no value; b and B are 1-byte signed and unsigned integers; ? is a 1-byte Boolean; h and H take 2 bytes; i, I, l and L take 4 bytes; q and Q take 8 bytes; e, f and d are 2-byte, 4-byte and 8-byte binary floating-point numbers in the IEEE 754 formats [271]; s is a byte string. A lowercase integer code is signed and the uppercase one unsigned. A number before a code repeats it, so 3H means three 2-byte unsigned integers, except that 4s means one string of 4 bytes. In native mode, l and L take the size of the C type long: 8 bytes on 64-bit Linux and 4 bytes on 64-bit Windows.

The functions:

In native mode, each field starts at the first offset that is a multiple of its type’s alignment on that machine, as a C compiler would lay out a structure. Padding goes only between fields: none at the start and none at the end.

Worked example

Take the header from above with version 1, length 300 and sequence number 0x12345678. In hexadecimal, 300 is 0x012c, because 1×256+44=3001 \times 256 + 44 = 300 and 44 is 0x2c.

struct.calcsize confirms the sizes: 1+2+4=71 + 2 + 4 = 7 with ! and <, and 1+1+2+4=81 + 1 + 2 + 4 = 8 with @.

Now send the bytes made with <BHI to a receiver that follows the specification and unpacks with !BHI. It reads the version correctly as 1, because a single byte has no byte order. It reads the length from 2c 01 as 𝟶𝚡𝟸𝚌𝟶𝟷=44×256+1=11265\texttt{0x2c01} = 44 \times 256 + 1 = 11265 instead of 300, and the sequence number from 78 56 34 12 as 0x78563412, which is 2018915346. Sent the 8 native bytes instead, struct.unpack("!BHI", data) raises struct.error because the buffer holds 8 bytes, not 7. A receiver that reads exactly 7 bytes from a stream gets the padding byte inside its length field, which it reads as 0x002c =44= 44, and leaves the eighth byte to be read as the start of the next message.

Signedness changes values in the same way: the 2 bytes ff ff unpack as −1-1 with <h and as 65535 with <H.

Stated precisely

For a format whose first character is <, >, ! or =, let its codes be c1,…,ckc_1, \dots, c_k, with standard sizes n1,…,nkn_1, \dots, n_k bytes. No padding is inserted, field jj starts at offset n1+…+nj−1n_1 + \dots + n_{j-1}, which is 0 for j=1j = 1, and calcsize returns n1+…+nkn_1 + \dots + n_k.

For an unsigned integer code of nn bytes, pack accepts a value vv with 0≤v≤28n−10 \le v \le 2^{8n} - 1. Write v=∑i=0n−1di⋅256iv = \sum_{i=0}^{n-1} d_i \cdot 256^{i}, where each digit did_i is a byte value from 0 to 255 and d0d_0 is the least significant byte. Little-endian output is d0,d1,…,dn−1d_0, d_1, \dots, d_{n-1}; big-endian output is dn−1,…,d1,d0d_{n-1}, \dots, d_1, d_0. For a signed code, pack accepts −28n−1≤v≤28n−1−1-2^{8n-1} \le v \le 2^{8n-1} - 1 and encodes vv as the unsigned value vmod28nv \bmod 2^{8n}, which is the two’s complement form; so −1-1 in 2 bytes becomes 65536−1=6553565536 - 1 = 65535, the bytes ff ff. A value outside its range makes pack raise struct.error.

For @ or no prefix, sizes are those of the C types on the machine running Python, and field jj starts at the smallest offset that is at least the end of field j−1j - 1 and is a multiple of the alignment of field jj’s C type. The encoding is then a function of the format, the values and the machine. With a standard prefix it is a function of the format and the values alone, which is the property a wire format needs. The guarantee assumes that both ends use the format the protocol specification defines.

Limits and common mistakes

The prefix fixes the encoding, not the meaning. struct does not check that a length of 300 is allowed, or that it matches the number of payload bytes that follow. Check every unpacked field against the specification before using it.

s fields truncate or pad without warning: struct.pack("4s", b"abcdef") gives b"abcd", and b"ab" is padded with two zero bytes. Check lengths before packing.

f rounds a Python float, which has 64 bits, to the nearest 32-bit value, so 0.1 does not come back as exactly the same Python float.

= gives standard sizes but the machine’s byte order, so it is still machine-dependent. ! means big-endian, not “whatever the network uses”: a protocol whose fields are little-endian, as in Bluetooth Low Energy §7.1 and USB, needs <.

struct has no codes for single bits or for fields of variable length. Bit fields are packed and extracted with shifts and masks, and a variable-length field takes its length from another field, as in length-prefix framing §4.30.

A C structure on the other machine is not a wire format either, because its compiler may insert struct padding §4.27. Follow the offsets of the specification, using x codes where it has reserved bytes, rather than a compiler’s structure layout.

A message authentication code §5.7 (MAC) must be computed over the bytes actually sent; a MAC over another encoding of the same values, such as a native-layout copy, does not protect the transmitted bytes. The authentication coverage §5.41 entry treats which bytes must be covered.

Questions answered

Why specify an explicit standard byte-order prefix for a wire format?

An explicit standard prefix is needed because without one, Python’s struct module encodes data in the layout of the machine running Python, while a wire format must produce the same bytes on every machine. With @ or no prefix, three things follow the machine: the byte order of multi-byte fields; the sizes of types such as l, which takes 8 bytes on 64-bit Linux and 4 on 64-bit Windows; and padding bytes inserted to align fields. The same call can therefore produce different bytes on two machines, and the other end decodes wrong values or the wrong number of bytes.

An explicit standard prefix, < for little-endian, or > or ! for big-endian, fixes the byte order, uses standard sizes and inserts no padding, so the bytes depend only on the format string and the values. On 64-bit Linux on an x86 processor, for example, @BHI packs version 1, length 300 and sequence number 0x12345678 into 8 bytes that include a padding byte, while !BHI packs them into the 7 bytes 01 01 2c 12 34 56 78 on every machine. Choose the prefix that the protocol specification states, and still check each field’s range and meaning, which no prefix does.

Related entries: Endianness (§4.21), Struct padding and packing (§4.27), Overflow-safe range check (§4.17), Authentication coverage (§5.41), Alignment (§4.22), Serialization (§4.28). Further reading: [36, 271].