From efb1f0918fad2ba3346a986b0e958dc5753a7bbe Mon Sep 17 00:00:00 2001 From: Ken Jin <28750310+Fidget-Spinner@users.noreply.github.com> Date: Tue, 29 Dec 2020 10:26:19 +0800 Subject: bpo-42740: Support PEP 604, 612 for typing.py get_args and get_origin (GH-23942) --- Lib/test/test_typing.py | 6 ++++++ Lib/typing.py | 8 +++++++- Misc/NEWS.d/next/Library/2020-12-25-23-23-11.bpo-42740.F0rQ_E.rst | 2 ++ 3 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2020-12-25-23-23-11.bpo-42740.F0rQ_E.rst diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py index 3dcc31f..3b8efe1 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -3021,6 +3021,7 @@ class GetUtilitiesTestCase(TestCase): self.assertIs(get_origin(Callable), collections.abc.Callable) self.assertIs(get_origin(list[int]), list) self.assertIs(get_origin(list), None) + self.assertIs(get_origin(list | str), types.Union) def test_get_args(self): T = TypeVar('T') @@ -3053,6 +3054,11 @@ class GetUtilitiesTestCase(TestCase): self.assertEqual(get_args(collections.abc.Callable[[], str]), ([], str)) self.assertEqual(get_args(collections.abc.Callable[[int], str]), get_args(Callable[[int], str])) + P = ParamSpec('P') + self.assertEqual(get_args(Callable[P, int]), (P, int)) + self.assertEqual(get_args(Callable[Concatenate[int, P], int]), + (Concatenate[int, P], int)) + self.assertEqual(get_args(list | str), (list, str)) class CollectionsAbcTests(BaseTestCase): diff --git a/Lib/typing.py b/Lib/typing.py index 67e95dd..d1db76f 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -1668,6 +1668,8 @@ def get_origin(tp): return tp.__origin__ if tp is Generic: return Generic + if isinstance(tp, types.Union): + return types.Union return None @@ -1686,9 +1688,13 @@ def get_args(tp): return (tp.__origin__,) + tp.__metadata__ if isinstance(tp, (_GenericAlias, GenericAlias)): res = tp.__args__ - if tp.__origin__ is collections.abc.Callable and res[0] is not Ellipsis: + if (tp.__origin__ is collections.abc.Callable + and not (res[0] is Ellipsis + or isinstance(res[0], (ParamSpec, _ConcatenateGenericAlias)))): res = (list(res[:-1]), res[-1]) return res + if isinstance(tp, types.Union): + return tp.__args__ return () diff --git a/Misc/NEWS.d/next/Library/2020-12-25-23-23-11.bpo-42740.F0rQ_E.rst b/Misc/NEWS.d/next/Library/2020-12-25-23-23-11.bpo-42740.F0rQ_E.rst new file mode 100644 index 0000000..588d90f --- /dev/null +++ b/Misc/NEWS.d/next/Library/2020-12-25-23-23-11.bpo-42740.F0rQ_E.rst @@ -0,0 +1,2 @@ +:func:`typing.get_args` and :func:`typing.get_origin` now support :pep:`604` +union types and :pep:`612` additions to ``Callable``. -- cgit v0.12