Skip to main content

Lib/struct.py (part 3)

Source:

cpython 3.14 @ ab2d84fe1023/Lib/struct.py

This annotation covers the module-level struct functions and Struct class caching. See modules_struct3_detail for Struct.pack_into, Struct.unpack_from, and Struct.iter_unpack.

Map

LinesSymbolRole
1-80struct.packPack values into bytes using a format string
81-160struct.unpackUnpack bytes into a tuple of values
161-240struct.calcsizeReturn the size of a format string in bytes
241-400Struct classCompiled struct format for repeated use

Reading

Module-level functions

# CPython: Lib/struct.py:1 (module-level wrappers)
# The module-level pack/unpack are thin wrappers around Struct objects.
# _struct (C extension) provides the real implementation.
from _struct import (
pack, pack_into, unpack, unpack_from, iter_unpack,
calcsize, error, Struct
)

struct.pack(fmt, *values) is equivalent to Struct(fmt).pack(*values). The C extension _struct provides all implementations; the struct Python module just re-exports them. The Struct class caches the compiled format, so repeated calls with the same format are efficient.

Format string reference

CharacterC typePython typeStandard size
bsigned charint1
Bunsigned charint1
hshortint2
Hunsigned shortint2
iintint4
Iunsigned intint4
llongint4
Lunsigned longint4
qlong longint8
Qunsigned long longint8
ffloatfloat4
ddoublefloat8
schar[]bytesvariable
pPascal stringbytesvariable
Pvoid *intnative

struct.error

// CPython: Modules/_struct.c:20 struct.error
static PyObject *StructError; /* exception class */

struct.error is raised for format string errors, size mismatches, and out-of-range values. It's a subclass of Exception. All struct operations raise this rather than ValueError or TypeError.

gopy notes

struct.pack is module/struct.Pack in module/struct/module.go. The format string is compiled to a []formatCode slice. Each format code stores the type char, count, and standard/native size. struct.error is objects.StructError.