summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorKen Jin <28750310+Fidget-Spinner@users.noreply.github.com>2020-12-29 02:26:19 (GMT)
committerGitHub <noreply@github.com>2020-12-29 02:26:19 (GMT)
commitefb1f0918fad2ba3346a986b0e958dc5753a7bbe (patch)
tree035a6ce4a6e3778e74a68ee6ea614190e20811e7
parenta6d63a20df63b3fd33b5e1f629e7f96d00f6ae39 (diff)
downloadcpython-efb1f0918fad2ba3346a986b0e958dc5753a7bbe.zip
cpython-efb1f0918fad2ba3346a986b0e958dc5753a7bbe.tar.gz
cpython-efb1f0918fad2ba3346a986b0e958dc5753a7bbe.tar.bz2
bpo-42740: Support PEP 604, 612 for typing.py get_args and get_origin (GH-23942)
-rw-r--r--Lib/test/test_typing.py6
-rw-r--r--Lib/typing.py8
-rw-r--r--Misc/NEWS.d/next/Library/2020-12-25-23-23-11.bpo-42740.F0rQ_E.rst2
3 files changed, 15 insertions, 1 deletions
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``.