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
| Lines | Symbol | Role |
|---|---|---|
| 1-80 | struct.pack | Pack values into bytes using a format string |
| 81-160 | struct.unpack | Unpack bytes into a tuple of values |
| 161-240 | struct.calcsize | Return the size of a format string in bytes |
| 241-400 | Struct class | Compiled 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
| Character | C type | Python type | Standard size |
|---|---|---|---|
b | signed char | int | 1 |
B | unsigned char | int | 1 |
h | short | int | 2 |
H | unsigned short | int | 2 |
i | int | int | 4 |
I | unsigned int | int | 4 |
l | long | int | 4 |
L | unsigned long | int | 4 |
q | long long | int | 8 |
Q | unsigned long long | int | 8 |
f | float | float | 4 |
d | double | float | 8 |
s | char[] | bytes | variable |
p | Pascal string | bytes | variable |
P | void * | int | native |
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.