On this page
  1. struct
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Precompiled Struct & Streaming Records (iter_unpack)
  7. 2. Zero-Copy Unpacking from memoryview / bytearray (unpack_from)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

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

Common Functions

Classes & Objects

Linked from

Related notes