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:
@, also used when the format has no prefix: native byte order, native sizes, native alignment.=: native byte order, standard sizes, no alignment.<: little-endian, standard sizes, no alignment.>: big-endian, standard sizes, no alignment.!: network byte order, which is big-endian; the same as>.
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:
struct.pack(fmt, v1, v2, ...)returns the bytes. It raisesstruct.errorwhen a value does not fit its code:struct.pack("<B", 256)fails because a 1-byte unsigned integer holds 0 to 255.struct.unpack(fmt, buf)returns a tuple of values. The buffer must be exactly as long as the layout, orstruct.erroris raised.struct.unpack_from(fmt, buf, offset)reads one layout that starts atoffsetin a longer buffer, which must hold at least that many bytes from there on;struct.pack_intowrites into an existing buffer.struct.calcsize(fmt)returns the number of bytes the layout takes.struct.Struct(fmt)prepares a format once for repeated use.
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 and 44 is 0x2c.
struct.pack("!BHI", 1, 300, 0x12345678)gives 7 bytes,01 01 2c 12 34 56 78: each multi-byte field starts with its most significant byte.struct.pack("<BHI", 1, 300, 0x12345678)gives 7 bytes,01 2c 01 78 56 34 12: the same values, with each multi-byte field starting with its least significant byte.struct.pack("@BHI", 1, 300, 0x12345678)on 64-bit Linux on an x86 processor gives 8 bytes,01 00 2c 01 78 56 34 12. The byte order is little-endian because that machine is little-endian, and a padding byte00follows the version because the 2-byte field must start at an even offset.
struct.calcsize confirms the sizes: with ! and <, and 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 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 , 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 with <h and as 65535 with <H.
Stated precisely
For a format whose first character is <, >, ! or =, let its codes be , with standard sizes bytes. No padding is inserted, field starts at offset , which is 0 for , and calcsize returns .
For an unsigned integer code of bytes, pack accepts a value with . Write , where each digit is a byte value from 0 to 255 and is the least significant byte. Little-endian output is ; big-endian output is . For a signed code, pack accepts and encodes as the unsigned value , which is the two’s complement form; so in 2 bytes becomes , 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 starts at the smallest offset that is at least the end of field and is a multiple of the alignment of field ’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].