GH-117750: When clearing object's dict, clear inline values but leave dict attached (GH-117808)

This commit is contained in:
Mark Shannon 2024-04-15 14:45:05 +01:00 committed by GitHub
parent 7d0be7aea5
commit 784e076a10
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 31 additions and 15 deletions

View File

@ -862,6 +862,16 @@ class TestInlineValues(unittest.TestCase):
self.assertFalse(has_inline_values(c)) self.assertFalse(has_inline_values(c))
self.check_100(c) self.check_100(c)
def test_bug_117750(self):
"Aborted on 3.13a6"
class C:
def __init__(self):
self.__dict__.clear()
obj = C()
self.assertEqual(obj.__dict__, {})
obj.foo = None # Aborted here
self.assertEqual(obj.__dict__, {"foo":None})
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -0,0 +1,3 @@
Fix issue where an object's dict would get out of sync with the object's
internal values when being cleared. ``obj.__dict__.clear()`` now clears the
internal values, but leaves the dict attached to the object.

View File

@ -2681,25 +2681,28 @@ clear_lock_held(PyObject *op)
interp, PyDict_EVENT_CLEARED, mp, NULL, NULL); interp, PyDict_EVENT_CLEARED, mp, NULL, NULL);
// We don't inc ref empty keys because they're immortal // We don't inc ref empty keys because they're immortal
ensure_shared_on_resize(mp); ensure_shared_on_resize(mp);
set_keys(mp, Py_EMPTY_KEYS);
set_values(mp, NULL);
mp->ma_used = 0;
mp->ma_version_tag = new_version; mp->ma_version_tag = new_version;
/* ...then clear the keys and values */ mp->ma_used = 0;
if (oldvalues != NULL) { if (oldvalues == NULL) {
if (!oldvalues->embedded) { set_keys(mp, Py_EMPTY_KEYS);
n = oldkeys->dk_nentries;
for (i = 0; i < n; i++)
Py_CLEAR(oldvalues->values[i]);
free_values(oldvalues, IS_DICT_SHARED(mp));
}
dictkeys_decref(interp, oldkeys, false);
}
else {
assert(oldkeys->dk_refcnt == 1); assert(oldkeys->dk_refcnt == 1);
dictkeys_decref(interp, oldkeys, IS_DICT_SHARED(mp)); dictkeys_decref(interp, oldkeys, IS_DICT_SHARED(mp));
} }
else {
n = oldkeys->dk_nentries;
for (i = 0; i < n; i++) {
Py_CLEAR(oldvalues->values[i]);
}
if (oldvalues->embedded) {
oldvalues->size = 0;
}
else {
set_values(mp, NULL);
set_keys(mp, Py_EMPTY_KEYS);
free_values(oldvalues, IS_DICT_SHARED(mp));
dictkeys_decref(interp, oldkeys, false);
}
}
ASSERT_CONSISTENT(mp); ASSERT_CONSISTENT(mp);
} }