From 3500b01fecc5eb9a9ac3ccc86ab69d836f63b61d Mon Sep 17 00:00:00 2001 From: sobolevn Date: Tue, 5 Mar 2024 02:10:34 +0300 Subject: [PATCH 1/2] gh-116325: Raise `SyntaxError` on ForwardRef with empty string arg --- Lib/test/test_typing.py | 6 ++++++ Lib/typing.py | 2 +- .../Library/2024-03-05-02-09-18.gh-issue-116325.FmlBYv.rst | 2 ++ 3 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2024-03-05-02-09-18.gh-issue-116325.FmlBYv.rst diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py index dbbbe63e95ad46..912384ab6bfe84 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -5867,6 +5867,12 @@ def foo(a: 'Node[T'): with self.assertRaises(SyntaxError): get_type_hints(foo) + def test_syntax_error_empty_string(self): + for form in [typing.List, typing.Set, typing.Type, typing.Deque]: + with self.subTest(form=form): + with self.assertRaises(SyntaxError): + form[''] + def test_name_error(self): def foo(a: 'Noode[T]'): diff --git a/Lib/typing.py b/Lib/typing.py index 2cb4a714ea3a85..42519363edec06 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -880,7 +880,7 @@ def __init__(self, arg, is_argument=True, module=None, *, is_class=False): # If we do `def f(*args: *Ts)`, then we'll have `arg = '*Ts'`. # Unfortunately, this isn't a valid expression on its own, so we # do the unpacking manually. - if arg[0] == '*': + if arg and arg[0] == '*': arg_to_compile = f'({arg},)[0]' # E.g. (*Ts,)[0] or (*tuple[int, int],)[0] else: arg_to_compile = arg diff --git a/Misc/NEWS.d/next/Library/2024-03-05-02-09-18.gh-issue-116325.FmlBYv.rst b/Misc/NEWS.d/next/Library/2024-03-05-02-09-18.gh-issue-116325.FmlBYv.rst new file mode 100644 index 00000000000000..aec4ee79b59cf2 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2024-03-05-02-09-18.gh-issue-116325.FmlBYv.rst @@ -0,0 +1,2 @@ +:mod:`typing`: raise :exc:`SyntaxError` instead of :exc:`AttributeError` +on forward references as empty strings. From 4d82edafafac9140b730348d4999921f4f54ba20 Mon Sep 17 00:00:00 2001 From: sobolevn Date: Tue, 5 Mar 2024 11:46:56 +0300 Subject: [PATCH 2/2] Use `.startswith` --- Lib/typing.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/typing.py b/Lib/typing.py index 42519363edec06..cca9525d632ea5 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -880,7 +880,7 @@ def __init__(self, arg, is_argument=True, module=None, *, is_class=False): # If we do `def f(*args: *Ts)`, then we'll have `arg = '*Ts'`. # Unfortunately, this isn't a valid expression on its own, so we # do the unpacking manually. - if arg and arg[0] == '*': + if arg.startswith('*'): arg_to_compile = f'({arg},)[0]' # E.g. (*Ts,)[0] or (*tuple[int, int],)[0] else: arg_to_compile = arg