Python Glossary Русский

all Python 3structterm

struct.Struct

format

A compiled struct format: parses the format string once and offers pack, unpack, iter_unpack and the size attribute.

Syntax

s = struct.Struct(format)  # s.pack(...), s.unpack(buf), s.size, s.format

The speed gain is smaller than it looks: the module-level struct functions cache recent formats themselves. The real benefit is that the record layout is declared once and named, and size replaces repeated calcsize calls. Without a byte-order prefix ('<', '>', '!') the sizes and layout are native with padding, so a file written on one machine may not read back on another.

Examples

import struct
rec = struct.Struct('<hI')  # short + unsigned int, little-endian
print(rec.size)  # → 6
data = rec.pack(-1, 7)
print(rec.unpack(data))  # → (-1, 7)
import struct
point = struct.Struct('<ff')
buf = point.pack(1.5, 2.0) + point.pack(3.0, 4.5)
print(list(point.iter_unpack(buf)))  # → [(1.5, 2.0), (3.0, 4.5)]

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy