bpo-44646: Fix the hash of the union type. (#27179)

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>
This commit is contained in:
Serhiy Storchaka 2021-07-16 11:34:56 +03:00 committed by GitHub
parent 919ad53751
commit aeaa553d65
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 12 additions and 4 deletions

View 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)

View File

@ -0,0 +1,2 @@
Fix the hash of the union type: it no longer depends on the order of
arguments.

View File

@ -36,11 +36,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