@@ -1457,7 +1457,7 @@ write_newline_indent(PyUnicodeWriter *writer,
14571457static PyObject *
14581458encoder_call (PyObject * op , PyObject * args , PyObject * kwds )
14591459{
1460- /* Python callable interface to encode_listencode_obj */
1460+ /* Python callable interface to encoder_listencode_obj */
14611461 static char * kwlist [] = {"obj" , "_current_indent_level" , NULL };
14621462 PyObject * obj ;
14631463 Py_ssize_t indent_level ;
@@ -1779,11 +1779,24 @@ _encoder_iterate_dict_lock_held(PyEncoderObject *s, PyUnicodeWriter *writer,
17791779 PyObject * key , * value ;
17801780 Py_ssize_t pos = 0 ;
17811781 while (PyDict_Next (dct , & pos , & key , & value )) {
1782+ #ifdef Py_GIL_DISABLED
1783+ // gh-119438: in the free-threading build the lock on dct can get suspended
1784+ Py_IncRef (key );
1785+ Py_IncRef (value );
1786+ #endif
17821787 if (encoder_encode_key_value (s , writer , first , dct , key , value ,
17831788 indent_level , indent_cache ,
17841789 separator ) < 0 ) {
1790+ #ifdef Py_GIL_DISABLED
1791+ Py_DecRef (key );
1792+ Py_DecRef (value );
1793+ #endif
17851794 return -1 ;
17861795 }
1796+ #ifdef Py_GIL_DISABLED
1797+ Py_DecRef (key );
1798+ Py_DecRef (value );
1799+ #endif
17871800 }
17881801 return 0 ;
17891802}
@@ -1887,15 +1900,28 @@ _encoder_iterate_fast_seq_lock_held(PyEncoderObject *s, PyUnicodeWriter *writer,
18871900{
18881901 for (Py_ssize_t i = 0 ; i < PySequence_Fast_GET_SIZE (s_fast ); i ++ ) {
18891902 PyObject * obj = PySequence_Fast_GET_ITEM (s_fast , i );
1903+ #ifdef Py_GIL_DISABLED
1904+ // gh-119438: in the free-threading build the lock on s_fast can get suspended
1905+ Py_IncRef (obj );
1906+ #endif
18901907 if (i ) {
18911908 if (PyUnicodeWriter_WriteStr (writer , separator ) < 0 ) {
1909+ #ifdef Py_GIL_DISABLED
1910+ Py_DecRef (obj );
1911+ #endif
18921912 return -1 ;
18931913 }
18941914 }
18951915 if (encoder_listencode_obj (s , writer , obj , indent_level , indent_cache )) {
18961916 _PyErr_FormatNote ("when serializing %T item %zd" , seq , i );
1917+ #ifdef Py_GIL_DISABLED
1918+ Py_DecRef (obj );
1919+ #endif
18971920 return -1 ;
18981921 }
1922+ #ifdef Py_GIL_DISABLED
1923+ Py_DecRef (obj );
1924+ #endif
18991925 }
19001926 return 0 ;
19011927}
0 commit comments