Skip to main content

struct

Interpret bytes as packed binary data. Convert between Python values and C structs represented as Python bytes objects.

Source-of-record: Modules/_struct.c, Lib/struct.py, struct docs.

Functions

FunctionEffect
pack(format, v1, v2, ...)Pack values into bytes.
unpack(format, buffer)Unpack to tuple; buffer must equal calcsize.
pack_into(format, buffer, offset, ...)Pack into a writable buffer at offset.
unpack_from(format, buffer, offset=0)Unpack from buffer at offset.
iter_unpack(format, buffer)Iterator of tuples.
calcsize(format)Size in bytes.
Struct(format)Pre-compile a format; reuse pack/unpack etc.

Byte order, size, alignment prefixes

CharByte orderSizeAlignment
@nativenativenative (default)
=nativestandardnone
<littlestandardnone
>bigstandardnone
!network (big)standardnone

Format characters

CharC typePython typeStandard size
xpad byte-1
ccharbytes of length 11
b / Bsigned/unsigned charint1
?_Boolbool1
h / Hshort/ushortint2
i / Iint/uintint4
l / Llong/ulongint4
q / Qlong longint8
n / Nssize_t/size_t (native only)int-
ehalf floatfloat2
f / dfloat/doublefloat4 / 8
schar[]bytescount
pPascal stringbytescount
Pvoid* (native)int-

A leading count multiplies the next format (e.g. 4i, 10s).

Struct class

s = Struct('<I H 4s')
buf = s.pack(1, 2, b'abcd')
i, h, b = s.unpack(buf)

Compiled Struct objects are faster for repeated use.

Errors

struct.error for malformed format strings, size mismatches, or out-of-range integers.

Gopy status

AreaState
All format characters incl. e, n/N, PComplete.
Byte-order prefixesComplete.
Native alignment with @Complete; matches the host C compiler layout.
Compiled Struct cacheComplete.

Reference

  • CPython 3.14: struct.
  • Modules/_struct.c.
  • module/_struct/. gopy port.