]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-44646: Fix the hash of the union type. (GH-27179) (#27180)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Fri, 16 Jul 2021 09:02:59 +0000 (02:02 -0700)
committerGitHub <noreply@github.com>
Fri, 16 Jul 2021 09:02:59 +0000 (11:02 +0200)
It no longer depends on the order of arguments.
hash(int | str) == hash(str | int)

Co-authored-by: Jack DeVries <58614260+jdevries3133@users.noreply.github.com>
(cherry picked from commit aeaa553d650786afc6e68df1f4813ae1a5b71d05)

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
Lib/test/test_types.py
Misc/NEWS.d/next/Core and Builtins/2021-07-16-09-59-13.bpo-44646.Yb6s05.rst [new file with mode: 0644]
Objects/unionobject.c

index 3f7677108ef2a881d7e87c086cf646084eb6115f..bb504122ba7968bd09f45ea7ee0a79b59f68e9eb 100644 (file)
@@ -663,6 +663,10 @@ class TypesTests(unittest.TestCase):
             x.__args__ = [str, int]
             (int | str ) == x
 
+    def test_hash(self):
+        self.assertEqual(hash(int | str), hash(str | int))
+        self.assertEqual(hash(int | str), hash(typing.Union[int, str]))
+
     def test_instancecheck(self):
         x = int | str
         self.assertIsInstance(1, x)
diff --git a/Misc/NEWS.d/next/Core and Builtins/2021-07-16-09-59-13.bpo-44646.Yb6s05.rst b/Misc/NEWS.d/next/Core and Builtins/2021-07-16-09-59-13.bpo-44646.Yb6s05.rst
new file mode 100644 (file)
index 0000000..0e28eac
--- /dev/null
@@ -0,0 +1,2 @@
+Fix the hash of the union type: it no longer depends on the order of
+arguments.
index 229b518ea757569e740ae320af76d98f979252ca..762df5d9780a388ef6b1ce0367ca88932de18b37 100644 (file)
@@ -33,11 +33,13 @@ static Py_hash_t
 union_hash(PyObject *self)
 {
     unionobject *alias = (unionobject *)self;
-    Py_hash_t h1 = PyObject_Hash(alias->args);
-    if (h1 == -1) {
-        return -1;
+    PyObject *args = PyFrozenSet_New(alias->args);
+    if (args == NULL) {
+        return (Py_hash_t)-1;
     }
-    return h1;
+    Py_hash_t hash = PyObject_Hash(args);
+    Py_DECREF(args);
+    return hash;
 }
 
 static int