Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Lib/test/test_io/test_memoryio.py
Original file line number Diff line number Diff line change
Expand Up @@ -967,6 +967,25 @@ def test_setstate(self):
memio.close()
self.assertRaises(ValueError, memio.__setstate__, ("closed", "", 0, None))

def test_write_str_subclass(self):
# Writing a str subclass should use the subclass's unicode data
# directly, not call __str__ on it (which may return a different
# value). gh-149047
class MyStr(str):
def __str__(self):
return "WRONG"

s = MyStr("correct")
memio = self.ioclass()
memio.write(s)
self.assertEqual(memio.getvalue(), "correct")

# Also test the fast path where pos == string_size (STATE_ACCUMULATING)
memio2 = self.ioclass()
memio2.write(MyStr("hello "))
memio2.write(MyStr("world"))
self.assertEqual(memio2.getvalue(), "hello world")


class CStringIOPickleTest(PyStringIOPickleTest):
UnsupportedOperation = io.UnsupportedOperation
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
:mod:`io`: Fix :class:`io.StringIO` serialization: no longer call ``str(obj)`` on :class:`str`
subclasses. Patch by Thomas Kowalski.
2 changes: 1 addition & 1 deletion Modules/_io/stringio.c
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ write_str(stringio *self, PyObject *obj)

if (self->state == STATE_ACCUMULATING) {
if (self->string_size == self->pos) {
if (PyUnicodeWriter_WriteStr(self->writer, decoded))
if (_PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)self->writer, decoded))
goto fail;
goto success;
}
Expand Down
Loading