diff --git a/Lib/test/test_capi/test_dict.py b/Lib/test/test_capi/test_dict.py index 9a2e79d4da7e71..e4121e6b11a494 100644 --- a/Lib/test/test_capi/test_dict.py +++ b/Lib/test/test_capi/test_dict.py @@ -635,11 +635,42 @@ class DictSubtype(dict): ... self.assertIs(type(d), DictSubtype) self.assertEqual(d, DictSubtype({})) + # non str keys: + d = {1: 'a', 2: 'b', 3: 'c', None: 'f'} + f = as_frozendict(d) + self.assertIs(type(f), frozendict) + self.assertEqual(f, frozendict({1: 'a', 2: 'b', 3: 'c', None: 'f'})) + self.assertIs(type(d), dict) + self.assertEqual(d, {}) + + d = DictSubtype({1: 'a', 2: 'b', 3: 'c', None: 'f'}) + f = as_frozendict(d) + self.assertIs(type(f), frozendict) + self.assertEqual(f, frozendict({1: 'a', 2: 'b', 3: 'c', None: 'f'})) + self.assertIs(type(d), DictSubtype) + self.assertEqual(d, DictSubtype({})) + + # wrong inputs: for wrong_input in (frozendict(), [], None): with self.subTest(wrong_input=wrong_input): with self.assertRaises(SystemError): as_frozendict(wrong_input) + # gh-161767: check embedded values + class Regular: ... + + for klass in (Regular, _testcapi.ManagedDictType): + with self.subTest(klass=klass): + instance = klass() + instance.key = 'value' + with self.assertRaisesRegex(ValueError, 'embedded values'): + as_frozendict(instance.__dict__) + + self.assertEqual(instance.__dict__, {'key': 'value'}) + # Both of these actions were needed to cause a crash: + instance.other = 'new' + del instance # must not crash + def test_frozendict_check(self): # Test PyFrozenDict_Check() check = _testcapi.frozendict_check diff --git a/Objects/dictobject.c b/Objects/dictobject.c index 5d3edbc4ed9578..f81242820a3d32 100644 --- a/Objects/dictobject.c +++ b/Objects/dictobject.c @@ -8700,6 +8700,13 @@ PyDict_AsFrozenDictAndClear(PyObject *dict) return NULL; } + PyDictObject *ma = (PyDictObject*)dict; + if (ma->ma_values && ma->ma_values->embedded) { + PyErr_SetString(PyExc_ValueError, + "can't convert dict with embedded values"); + return NULL; + } + PyObject *res = frozendict_new_untracked(&PyFrozenDict_Type); if (res == NULL) { return NULL;