[Python-checkins] bpo-44704: Make Set._hash consistent with frozenset.__hash__ (GH-27281) (GH-27282)

rhettinger webhook-mailer at python.org
Wed Jul 21 20:23:48 EDT 2021


https://github.com/python/cpython/commit/4194f1465fa85371dcbead57a54bb06d1f0b97d9
commit: 4194f1465fa85371dcbead57a54bb06d1f0b97d9
branch: 3.10
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: rhettinger <rhettinger at users.noreply.github.com>
date: 2021-07-21T19:23:21-05:00
summary:

bpo-44704: Make Set._hash consistent with frozenset.__hash__ (GH-27281) (GH-27282)

files:
A Misc/NEWS.d/next/Library/2021-07-21-23-16-30.bpo-44704.iqHLxQ.rst
M Lib/_collections_abc.py
M Lib/test/test_collections.py

diff --git a/Lib/_collections_abc.py b/Lib/_collections_abc.py
index d92b848e9436f..bff58ad4a7f6a 100644
--- a/Lib/_collections_abc.py
+++ b/Lib/_collections_abc.py
@@ -696,6 +696,7 @@ def _hash(self):
             hx = hash(x)
             h ^= (hx ^ (hx << 16) ^ 89869747)  * 3644798167
             h &= MASK
+        h ^= (h >> 11) ^ (h >> 25)
         h = h * 69069 + 907133923
         h &= MASK
         if h > MAX:
diff --git a/Lib/test/test_collections.py b/Lib/test/test_collections.py
index f98048b34a7a1..1f659d7d604e3 100644
--- a/Lib/test/test_collections.py
+++ b/Lib/test/test_collections.py
@@ -1801,6 +1801,18 @@ def __repr__(self):
         self.assertTrue(f1 != l1)
         self.assertTrue(f1 != l2)
 
+    def test_Set_hash_matches_frozenset(self):
+        sets = [
+            {}, {1}, {None}, {-1}, {0.0}, {"abc"}, {1, 2, 3},
+            {10**100, 10**101}, {"a", "b", "ab", ""}, {False, True},
+            {object(), object(), object()}, {float("nan")},  {frozenset()},
+            {*range(1000)}, {*range(1000)} - {100, 200, 300},
+            {*range(sys.maxsize - 10, sys.maxsize + 10)},
+        ]
+        for s in sets:
+            fs = frozenset(s)
+            self.assertEqual(hash(fs), Set._hash(fs), msg=s)
+
     def test_Mapping(self):
         for sample in [dict]:
             self.assertIsInstance(sample(), Mapping)
diff --git a/Misc/NEWS.d/next/Library/2021-07-21-23-16-30.bpo-44704.iqHLxQ.rst b/Misc/NEWS.d/next/Library/2021-07-21-23-16-30.bpo-44704.iqHLxQ.rst
new file mode 100644
index 0000000000000..586661876dedb
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2021-07-21-23-16-30.bpo-44704.iqHLxQ.rst
@@ -0,0 +1 @@
+The implementation of ``collections.abc.Set._hash()`` now matches that of ``frozenset.__hash__()``.
\ No newline at end of file



More information about the Python-checkins mailing list