python / python/cpython

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

Open
#148,529 7 comments 0 reactions 1 assignee View on GitHub

@serhiy-storchaka is already working on this.

Since Apr 14, 2026.

extension-modules type-bug type-feature
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

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

https://github.com/python/cpython/blob/9a89f1bf1e7bb819fe7240be779c99a84f47ea46/Modules/_struct.c#L1936-L1941

CPython versions tested on:

3.14

Operating systems tested on:

macOS

Linked PRs
  • gh-148565
  • gh-149063
  • gh-149072
  • gh-152029

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.