Skip to content

Conversation

@LindaSummer
Copy link
Contributor

@LindaSummer LindaSummer commented Dec 13, 2025

Issue

#142495

Proposed Changes

  • Use PyDict_SetDefaultRef to guard the object update and keep existed value.
  • Add a test case for the racing case

Comment

The PyDict_SetDefaultRef would increase the reference count of the setted item, so we must decrement the refrence count on __missing__ created object to avoid memory leak.

Comment on lines 2234 to 2241
PyObject* result;
PyDict_SetDefaultRef(op, key, value, &result);
// when PyDict_SetDefaultRef() < 0, result will be NULL
// when PyDict_SetDefaultRef() == 0, result is a new reference of default value
// when PyDict_SetDefaultRef() > 0, result is a new reference to the existing value
// so the value reference must be decref'ed in all cases
Py_DECREF(value);
return result;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
PyObject* result;
PyDict_SetDefaultRef(op, key, value, &result);
// when PyDict_SetDefaultRef() < 0, result will be NULL
// when PyDict_SetDefaultRef() == 0, result is a new reference of default value
// when PyDict_SetDefaultRef() > 0, result is a new reference to the existing value
// so the value reference must be decref'ed in all cases
Py_DECREF(value);
return result;
PyObject *result = NULL;
(void)PyDict_SetDefaultRef(op, key, value, &result);
// 'result' is NULL, or a strong reference to 'value' or 'op[key]'
Py_DECREF(value);
return result;

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @picnixz ,

Thanks very much for your suggestion! ❤
I have updated this part as suggested.

Best Regards,
Edward

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants