Skip to content

struct.pack with format s errors on bytes-like data #148529

@jakirkham

Description

@jakirkham

Bug report

Bug description:

When using struct.pack with format s, it works with bytes and bytearray. However other bytes-like data (such as memoryview) is not handled raising an error. Here is some sample code show this issue

import struct

b = b"abad"

struct. pack("4s", b)               # Ok
struct. pack("4s", bytearray(b))    # Ok
struct. pack("4s", memoryview(b))   # Error

This code appears to contain the corresponding logic

cpython/Modules/_struct.c

Lines 1936 to 1941 in 9a89f1b

isstring = PyBytes_Check(v);
if (!isstring && !PyByteArray_Check(v)) {
PyErr_SetString(state->StructError,
"argument for 's' must be a bytes object");
return -1;
}

CPython versions tested on:

3.14

Operating systems tested on:

macOS

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulesC modules in the Modules dirtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions