Skip to content

Failed BytesIO reinitialization mutates the stream's position and contents #157048

Description

@ngoldbaum

Bug report

Bug description:

Python 3.16.0a0 (heads/main:09117bc, Sep  6 2026, 15:04:05) [Clang 21.0.0 (clang-2100.1.1.101)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import io
...
... stream = io.BytesIO(b"abcd")
... stream.seek(2)
... view = stream.getbuffer()
... try:
...     stream.__init__(b"replacement")
... except BufferError:
...     pass
... print(stream.tell(), stream.getvalue(), bytes(view))
... # 0 b'' b'abcd'
... view.release()
...
0 b'' b'abcd'

This is happening because the implementation of BytesIO.__init__ resets state before checking for the BufferError:

cpython/Modules/_io/bytesio.c

Lines 1129 to 1137 in 09117bc

/* In case, __init__ is called multiple times. */
self->string_size = 0;
self->pos = 0;
if (FT_ATOMIC_LOAD_SSIZE_RELAXED(self->exports) > 0) {
PyErr_SetString(PyExc_BufferError,
"Existing exports of data: object cannot be re-sized");
return -1;
}

CPython versions tested on:

3.16, CPython main branch

Operating systems tested on:

macOS

Linked PRs

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

stdlibStandard Library Python modules in the Lib/ directorytopic-IOtype-bugAn unexpected behavior, bug, or error

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions