Skip to content

Commit 97a77b7

Browse files
eendebakptclaude
andcommitted
Do not materialize an empty instance dict in BytesIO/StringIO.__getstate__
Check _PyObject_IsInstanceDictEmpty() first, as object.__getstate__() does, instead of creating an empty dict just to find out that it is empty. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
1 parent 60955ab commit 97a77b7

2 files changed

Lines changed: 14 additions & 14 deletions

File tree

‎Modules/_io/bytesio.c‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -971,15 +971,15 @@ _io_BytesIO___getstate___impl(bytesio *self)
971971

972972
if (initvalue == NULL)
973973
return NULL;
974-
dict = PyObject_GenericGetDict((PyObject *)self, NULL);
975-
if (dict == NULL) {
976-
Py_DECREF(initvalue);
977-
return NULL;
978-
}
979-
if (PyDict_GET_SIZE(dict) == 0) {
980-
Py_SETREF(dict, Py_NewRef(Py_None));
974+
if (_PyObject_IsInstanceDictEmpty((PyObject *)self)) {
975+
dict = Py_NewRef(Py_None);
981976
}
982977
else {
978+
dict = PyObject_GenericGetDict((PyObject *)self, NULL);
979+
if (dict == NULL) {
980+
Py_DECREF(initvalue);
981+
return NULL;
982+
}
983983
Py_SETREF(dict, PyDict_Copy(dict));
984984
if (dict == NULL) {
985985
Py_DECREF(initvalue);

‎Modules/_io/stringio.c‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -927,15 +927,15 @@ _io_StringIO___getstate___impl(stringio *self)
927927

928928
if (initvalue == NULL)
929929
return NULL;
930-
dict = PyObject_GenericGetDict((PyObject *)self, NULL);
931-
if (dict == NULL) {
932-
Py_DECREF(initvalue);
933-
return NULL;
934-
}
935-
if (PyDict_GET_SIZE(dict) == 0) {
936-
Py_SETREF(dict, Py_NewRef(Py_None));
930+
if (_PyObject_IsInstanceDictEmpty((PyObject *)self)) {
931+
dict = Py_NewRef(Py_None);
937932
}
938933
else {
934+
dict = PyObject_GenericGetDict((PyObject *)self, NULL);
935+
if (dict == NULL) {
936+
Py_DECREF(initvalue);
937+
return NULL;
938+
}
939939
Py_SETREF(dict, PyDict_Copy(dict));
940940
if (dict == NULL) {
941941
Py_DECREF(initvalue);

0 commit comments

Comments
 (0)