On this page
struct
Prev: stringprep | Up: stdlib_module | Next: subprocess
Rel: codecs
Ref: docs.python.org — struct
Tags: #public #python3 #stdlib
Import
import struct
Overview
Packs Python values into fixed-layout C binary bytes and unpacks binary protocols, file headers, and network frames back into Python tuples (pack, unpack, iter_unpack, calcsize, Struct). Always prefix format strings with an explicit byte order (> big-endian/network, < little-endian, ! network).
Quick Start
import struct
# Big-endian: unsigned short (H) + unsigned int (I) + 4-byte ASCII tag (4s)
header = struct.pack(">HI4s", 1, 4096, b"DATA")
assert len(header) == struct.calcsize(">HI4s") == 10
version, length, tag = struct.unpack(">HI4s", header)
assert (version, length, tag) == (1, 4096, b"DATA")
Implementation Walkthrough
1. Precompiled Struct & Streaming Records (iter_unpack)
Precompile a Struct object when packing/unpacking in a loop so the format string is parsed only once:
import struct
POINT = struct.Struct("<ff") # two little-endian 32-bit floats (8 bytes)
raw = POINT.pack(1.5, -2.0) + POINT.pack(3.0, 4.5)
points = list(POINT.iter_unpack(raw))
assert points == [(1.5, -2.0), (3.0, 4.5)]
2. Zero-Copy Unpacking from memoryview / bytearray (unpack_from)
import struct
buf = bytearray(16)
struct.pack_into(">I", buf, 4, 0xDEADBEEF)
assert struct.unpack_from(">I", buf, 4) == (0xDEADBEEF,)
Gotchas & Boundaries
- Always specify explicit byte order (
<,>, or!): Omitting it uses native alignment and endianness, which inserts platform-dependent padding bytes and breaks cross-machine binary files. unpack()always returns a tuple, even for a single field ((val,) = struct.unpack(">I", raw)).sformat pads with\x00or truncates silently:struct.pack("4s", b"ABCDEF")silently truncates tob"ABCD".- Buffer length must match
calcsize()exactly forunpack(), orstruct.erroris raised.
Common Functions
- struct.calcsize() —
calcsize(format, /)— Return size in bytes of the struct described by the format string. - struct.iter_unpack() —
iter_unpack(format, buffer, /)— Return an iterator yielding tuples unpacked from the given bytes. - struct.pack() —
pack(format, v1, v2, ...) -> bytes— Return a bytes object containing the values v1, v2, ... packed according to the format string. See help(struct) for more on format strings. - struct.pack_into() —
pack_into(format, buffer, offset, v1, v2, ...)— Pack the values v1, v2, ... according to the format string and write the packed bytes into the writable buffer buf starting at offset. Note that the offset is a required argument. A negative offset counts from - struct.unpack() —
unpack(format, buffer, /)— Return a tuple containing values unpacked according to the format string. - struct.unpack_from() —
unpack_from(format, /, buffer, offset=0)— Return a tuple containing values unpacked according to the format string.
Classes & Objects
- struct.error —
struct.errorclass. (Methods:.add_note(),.with_traceback()) - struct.Struct — Struct(fmt) --> compiled struct object (Methods:
.iter_unpack(),.pack(),.pack_into(),.unpack(),.unpack_from())
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/array
- tuts/python3/stdlib_module/codecs
- tuts/python3/stdlib_module/pickle
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/stringprep
- tuts/python3/stdlib_module/subprocess
- tuts/python3/stdlib_module/wave
- tuts/python3/tutorials/advanced_python_internals/foreign_function_interfaces
Related notes
- tuts/python3/stdlib_module/codecs Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stringprep Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/subprocess Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/array links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pickle links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/struct/calcsize Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/struct/error Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/struct/iter_unpack Linked here; shared tags: #stdlib