Python Glossary Русский

all Python 3structfunction

struct.pack_into()

packing and unpacking

Packs values by a struct format directly into a writable buffer (bytearray, memoryview) starting at a given offset.

Syntax

struct.pack_into(format, buffer, offset, v1, v2, ...)

It returns nothing — the result lives in the buffer itself, so x = pack_into(...) gives None. bytes is immutable, so you need a bytearray or a memoryview, otherwise TypeError. The buffer never grows: if there is not enough room after offset you get struct.error, not an extension.

Examples

import struct
buf = bytearray(6)
print(struct.pack_into('<HH', buf, 2, 1, 513))  # → None
print(buf)  # → bytearray(b'\x00\x00\x01\x00\x01\x02')
import struct
try:
    struct.pack_into('<I', b'1234', 0, 1)
except TypeError as e:
    print(e)  # → must be read-write bytes-like object, not bytes

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy