diff options
author | Pablo Galindo Salgado <Pablogsal@gmail.com> | 2021-07-24 14:08:53 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-07-24 14:08:53 (GMT) |
commit | 9356d1e47de583fd794e9d29abc448759f7a4109 (patch) | |
tree | dd61cac33c0eba84bf94a22a9c63a97f6c4e5041 /Lib | |
parent | e8c01749c02a97a2f5b01086951bb564121c5113 (diff) | |
download | cpython-9356d1e47de583fd794e9d29abc448759f7a4109.zip cpython-9356d1e47de583fd794e9d29abc448759f7a4109.tar.gz cpython-9356d1e47de583fd794e9d29abc448759f7a4109.tar.bz2 |
[3.10] bpo-44676: Add ability to serialize types.Union (GH-27244) (GH-27333)
(cherry picked from commit fe13f0b0f696464dd6f283576668dbf57cb11399)
Co-authored-by: Yurii Karabas <1998uriyyo@gmail.com>
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/test/test_types.py | 35 | ||||
-rw-r--r-- | Lib/typing.py | 4 |
2 files changed, 37 insertions, 2 deletions
diff --git a/Lib/test/test_types.py b/Lib/test/test_types.py index 99b011e..d149e6b 100644 --- a/Lib/test/test_types.py +++ b/Lib/test/test_types.py @@ -13,6 +13,9 @@ import unittest.mock import weakref import typing + +T = typing.TypeVar("T") + class Example: pass @@ -802,6 +805,38 @@ class UnionTests(unittest.TestCase): eq(x[NT], int | NT | bytes) eq(x[S], int | S | bytes) + def test_union_pickle(self): + alias = list[T] | int + s = pickle.dumps(alias) + loaded = pickle.loads(s) + self.assertEqual(alias, loaded) + self.assertEqual(alias.__args__, loaded.__args__) + self.assertEqual(alias.__parameters__, loaded.__parameters__) + + def test_union_from_args(self): + with self.assertRaisesRegex( + TypeError, + r"^Each union argument must be a type, got 1$", + ): + types.Union._from_args((1,)) + + with self.assertRaisesRegex( + TypeError, + r"Union._from_args\(\) argument 'args' must be tuple, not int$", + ): + types.Union._from_args(1) + + with self.assertRaisesRegex(ValueError, r"args must be not empty"): + types.Union._from_args(()) + + alias = types.Union._from_args((int, str, T)) + + self.assertEqual(alias.__args__, (int, str, T)) + self.assertEqual(alias.__parameters__, (T,)) + + result = types.Union._from_args((int,)) + self.assertIs(int, result) + def test_union_parameter_substitution_errors(self): T = typing.TypeVar("T") x = int | T diff --git a/Lib/typing.py b/Lib/typing.py index ffd35e5..e2fb7d1 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -321,7 +321,7 @@ def _eval_type(t, globalns, localns, recursive_guard=frozenset()): if isinstance(t, GenericAlias): return GenericAlias(t.__origin__, ev_args) if isinstance(t, types.Union): - return functools.reduce(operator.or_, ev_args) + return types.Union._from_args(ev_args) else: return t.copy_with(ev_args) return t @@ -1800,7 +1800,7 @@ def _strip_annotations(t): stripped_args = tuple(_strip_annotations(a) for a in t.__args__) if stripped_args == t.__args__: return t - return functools.reduce(operator.or_, stripped_args) + return types.Union._from_args(stripped_args) return t |