From 75d2d945b4e28ca34506b2d4902367b61a8dff82 Mon Sep 17 00:00:00 2001 From: Gregory Beauregard Date: Wed, 2 Mar 2022 17:14:52 -0800 Subject: bpo-46643: Fix stringized P.args/P.kwargs with get_type_hints (GH-31238) --- Lib/test/test_typing.py | 12 ++++++++++++ Lib/typing.py | 3 ++- .../next/Library/2022-02-09-22-40-11.bpo-46643.aBlIx1.rst | 1 + 3 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2022-02-09-22-40-11.bpo-46643.aBlIx1.rst diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py index 8fcc24c..bd99204 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -5187,6 +5187,18 @@ class ParamSpecTests(BaseTestCase): self.assertEqual(repr(P.args), "P.args") self.assertEqual(repr(P.kwargs), "P.kwargs") + def test_stringized(self): + P = ParamSpec('P') + class C(Generic[P]): + func: Callable["P", int] + def foo(self, *args: "P.args", **kwargs: "P.kwargs"): + pass + + self.assertEqual(gth(C, globals(), locals()), {"func": Callable[P, int]}) + self.assertEqual( + gth(C.foo, globals(), locals()), {"args": P.args, "kwargs": P.kwargs} + ) + def test_user_generics(self): T = TypeVar("T") P = ParamSpec("P") diff --git a/Lib/typing.py b/Lib/typing.py index 9d668b3..6e0c68c 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -181,7 +181,8 @@ def _type_check(arg, msg, is_argument=True, module=None, *, allow_special_forms= return arg if isinstance(arg, _SpecialForm) or arg in (Generic, Protocol): raise TypeError(f"Plain {arg} is not valid as type argument") - if isinstance(arg, (type, TypeVar, ForwardRef, types.UnionType, ParamSpec)): + if isinstance(arg, (type, TypeVar, ForwardRef, types.UnionType, ParamSpec, + ParamSpecArgs, ParamSpecKwargs)): return arg if not callable(arg): raise TypeError(f"{msg} Got {arg!r:.100}.") diff --git a/Misc/NEWS.d/next/Library/2022-02-09-22-40-11.bpo-46643.aBlIx1.rst b/Misc/NEWS.d/next/Library/2022-02-09-22-40-11.bpo-46643.aBlIx1.rst new file mode 100644 index 0000000..e8b4d66 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2022-02-09-22-40-11.bpo-46643.aBlIx1.rst @@ -0,0 +1 @@ +In :func:`typing.get_type_hints`, support evaluating stringified ``ParamSpecArgs`` and ``ParamSpecKwargs`` annotations. Patch by Gregory Beauregard. \ No newline at end of file -- cgit v0.12