8000 [3.10] bpo-44636: Collapse union of equal types (GH-27178) (GH-27181) · python/cpython@c3007ab · GitHub
[go: up one dir, main page]

Skip to content

Commit c3007ab

Browse files
[3.10] bpo-44636: Collapse union of equal types (GH-27178) (GH-27181)
The result of `int | int` is now `int`. Fix comparison of the union type with non-hashable objects. `int | str == {}` no longer raises a TypeError. (cherry picked from commit d9f9232)
1 parent 37686f7 commit c3007ab

File tree

3 files changed

+20
-9
lines changed

3 files changed

+20
-9
lines changed

Lib/test/test_types.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -623,7 +623,7 @@ def test_or_types_operator(self):
623623
self.assertEqual(None | typing.List[int], typing.Union[None, typing.List[int]])
624624
self.assertEqual(str | float | int | complex | int, (int | str) | (float | complex))
625625
self.assertEqual(typing.Union[str, int, typing.List[int]], str | int | typing.List[int])
626-
self.assertEqual(int | int, int)
626+
self.assertIs(int | int, int)
627627
self.assertEqual(
628628
BaseException |
629629
bool |
@@ -651,6 +651,8 @@ def test_or_types_operator(self):
651651
3 | int
652652
with self.assertRaises(TypeError):
653653
Example() | int
654+
x = int | str
655+
self.assertNotEqual(x, {})
654656
with self.assertRaises(TypeError):
655657
(int | str) < typing.Union[str, int]
656658
with self.assertRaises(TypeError):
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Collapse union of equal types. E.g. the result of ``int | int`` is now ``int``. Fix comparison of the union type with non-hashable objects. E.g. ``int | str == {}`` no longer raises a TypeError.

Objects/unionobject.c

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -184,9 +184,9 @@ union_richcompare(PyObject *a, PyObject *b, int op)
184184
}
185185
}
186186
} else {
187-
if (PySet_Add(b_set, b) == -1) {
188-
goto exit;
189-
}
187+
Py_DECREF(a_set);
188+
Py_DECREF(b_set);
189+
Py_RETURN_NOTIMPLEMENTED;
190190
}
191191
result = PyObject_RichCompare(a_set, b_set, op);
192192
exit:
@@ -499,16 +499,24 @@ _Py_Union(PyObject *args)
499499
}
500500
}
501501

502+
args = dedup_and_flatten_args(args);
503+
if (args == NULL) {
504+
return NULL;
505+
}
506+
if (PyTuple_GET_SIZE(args) == 1) {
507+
PyObject *result1 = PyTuple_GET_ITEM(args, 0);
508+
Py_INCREF(result1);
509+
Py_DECREF(args);
510+
return result1;
511+
}
512+
502513
result = PyObject_GC_New(unionobject, &_Py_UnionType);
503514
if (result == NULL) {
515+
Py_DECREF(args);
504516
return NULL;
505517
}
506518

507-
result->args = dedup_and_flatten_args(args);
519+
result->args = args;
508520
_PyObject_GC_TRACK(result);
509-
if (result->args == NULL) {
510-
Py_DECREF(result);
511-
return NULL;
512-
}
513521
return (PyObject*)result;
514522
}

0 commit comments

Comments
 (0)
0