From e1c09fff054ebcb90e72bba25ef7332bcabec92b Mon Sep 17 00:00:00 2001 From: Jelle Zijlstra Date: Thu, 24 Apr 2025 09:49:09 -0700 Subject: [PATCH] gh-132882: Fix copying of unions with members that do not support __or__ (#132883) --- Lib/copyreg.py | 4 ++-- Lib/test/test_typing.py | 10 ++++++---- .../2025-04-24-09-10-04.gh-issue-132882.6zoyp5.rst | 2 ++ 3 files changed, 10 insertions(+), 6 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2025-04-24-09-10-04.gh-issue-132882.6zoyp5.rst diff --git a/Lib/copyreg.py b/Lib/copyreg.py index 17c5dde67c8..a5e8add4a55 100644 --- a/Lib/copyreg.py +++ b/Lib/copyreg.py @@ -31,8 +31,8 @@ def pickle_complex(c): pickle(complex, pickle_complex, complex) def pickle_union(obj): - import functools, operator - return functools.reduce, (operator.or_, obj.__args__) + import typing, operator + return operator.getitem, (typing.Union, obj.__args__) pickle(type(int | str), pickle_union) diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py index 4fd3d53b72c..93cc2a8ca83 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -5283,10 +5283,12 @@ class GenericTests(BaseTestCase): Tuple[Any, Any], Node[T], Node[int], Node[Any], typing.Iterable[T], typing.Iterable[Any], typing.Iterable[int], typing.Dict[int, str], typing.Dict[T, Any], ClassVar[int], ClassVar[List[T]], Tuple['T', 'T'], - Union['T', int], List['T'], typing.Mapping['T', int]] - for t in things + [Any]: - self.assertEqual(t, copy(t)) - self.assertEqual(t, deepcopy(t)) + Union['T', int], List['T'], typing.Mapping['T', int], + Union[b"x", b"y"], Any] + for t in things: + with self.subTest(thing=t): + self.assertEqual(t, copy(t)) + self.assertEqual(t, deepcopy(t)) def test_immutability_by_copy_and_pickle(self): # Special forms like Union, Any, etc., generic aliases to containers like List, diff --git a/Misc/NEWS.d/next/Library/2025-04-24-09-10-04.gh-issue-132882.6zoyp5.rst b/Misc/NEWS.d/next/Library/2025-04-24-09-10-04.gh-issue-132882.6zoyp5.rst new file mode 100644 index 00000000000..a93469fdcf9 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-04-24-09-10-04.gh-issue-132882.6zoyp5.rst @@ -0,0 +1,2 @@ +Fix copying of :class:`typing.Union` objects containing objects that do not +support the ``|`` operator.