Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Lib/test/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -1902,6 +1902,17 @@ def test_hash(self):
with self.assertRaisesRegex(TypeError, "unhashable type: 'list'"):
hash(fd)

def test_hash_pipe_operator(self):
# gh-149676: frozendict created via | must have the same hash as one
# created directly with the same contents (ma_hash must be initialised
# to -1 so that the hash is computed on first call, not left as garbage)
a = frozendict({"a": 1})
b = frozendict({"b": 2})
c = frozendict({"a": 1, "b": 2})
c_union = a | b
self.assertEqual(c, c_union)
self.assertEqual(hash(c), hash(c_union))

def test_fromkeys(self):
self.assertEqual(frozendict.fromkeys('abc'),
frozendict(a=None, b=None, c=None))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix :class:`frozendict` instances being created with an uninitialised hash value, which could cause incorrect hash lookups or crashes.
8 changes: 7 additions & 1 deletion Objects/dictobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -940,7 +940,13 @@ new_frozendict(PyDictKeysObject *keys, PyDictValues *values,
Py_ssize_t used, int free_values_on_failure)
{
PyDictObject *mp = PyObject_GC_New(PyDictObject, &PyFrozenDict_Type);
return new_dict_impl(mp, keys, values, used, free_values_on_failure);
PyObject *result = new_dict_impl(mp, keys, values, used, free_values_on_failure);
if (result != NULL) {
/* ma_hash must be -1 (sentinel for "not computed") since PyObject_GC_New
does not zero-initialize memory and new_dict_impl does not touch ma_hash. */
_PyFrozenDictObject_CAST(result)->ma_hash = -1;
}
return result;
}

static PyObject *
Expand Down
Loading