]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.11] gh-116325: Raise `SyntaxError` rather than `IndexError` on ForwardRef with...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Tue, 5 Mar 2024 10:15:54 +0000 (11:15 +0100)
committerGitHub <noreply@github.com>
Tue, 5 Mar 2024 10:15:54 +0000 (10:15 +0000)
gh-116325: Raise `SyntaxError` rather than `IndexError` on ForwardRef with empty string arg (GH-116341)
(cherry picked from commit a29998a06bf75264c3faaeeec4584a5f75b45a1f)

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
Lib/test/test_typing.py
Lib/typing.py
Misc/NEWS.d/next/Library/2024-03-05-02-09-18.gh-issue-116325.FmlBYv.rst [new file with mode: 0644]

index b2e4c901b737ee3765cd63a48d9d33a4f3a9c519..ab430e3f76d150af174a79cee2e73d95d27cb136 100644 (file)
@@ -4953,6 +4953,12 @@ class ForwardRefTests(BaseTestCase):
         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]'):
index 45c6fbde46af54792c915db4a12e083d0da422fe..e3c9e6e786721056796a6ff44de7b6500cad0b09 100644 (file)
@@ -870,7 +870,7 @@ class ForwardRef(_Final, _root=True):
         # 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.startswith('*'):
             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 (file)
index 0000000..aec4ee7
--- /dev/null
@@ -0,0 +1,2 @@
+:mod:`typing`: raise :exc:`SyntaxError` instead of :exc:`AttributeError`
+on forward references as empty strings.