[Python-checkins] bpo-44646: Fix the hash of the union type. (GH-27179) (#27180)
ambv
webhook-mailer at python.org
Fri Jul 16 05:03:16 EDT 2021
https://github.com/python/cpython/commit/705988056e028bab3dbc5cff3671a8ddefc88ec7
commit: 705988056e028bab3dbc5cff3671a8ddefc88ec7
branch: 3.10
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: ambv <lukasz at langa.pl>
date: 2021-07-16T11:02:59+02:00
summary:
bpo-44646: Fix the hash of the union type. (GH-27179) (#27180)
It no longer depends on the order of arguments.
hash(int | str) == hash(str | int)
Co-authored-by: Jack DeVries <58614260+jdevries3133 at users.noreply.github.com>
(cherry picked from commit aeaa553d650786afc6e68df1f4813ae1a5b71d05)
Co-authored-by: Serhiy Storchaka <storchaka at gmail.com>
files:
A Misc/NEWS.d/next/Core and Builtins/2021-07-16-09-59-13.bpo-44646.Yb6s05.rst
M Lib/test/test_types.py
M Objects/unionobject.c
diff --git a/Lib/test/test_types.py b/Lib/test/test_types.py
index 3f7677108ef2a..bb504122ba796 100644
--- a/Lib/test/test_types.py
+++ b/Lib/test/test_types.py
@@ -663,6 +663,10 @@ def test_or_types_operator(self):
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
index 0000000000000..0e28eac54fe98
--- /dev/null
+++ b/Misc/NEWS.d/next/Core and Builtins/2021-07-16-09-59-13.bpo-44646.Yb6s05.rst
@@ -0,0 +1,2 @@
+Fix the hash of the union type: it no longer depends on the order of
+arguments.
diff --git a/Objects/unionobject.c b/Objects/unionobject.c
index 229b518ea7575..762df5d9780a3 100644
--- a/Objects/unionobject.c
+++ b/Objects/unionobject.c
@@ -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
More information about the Python-checkins
mailing list