summaryrefslogtreecommitdiffstats
path: root/Lib/test/test_syntax.py
diff options
context:
space:
mode:
authorsobolevn <mail@sobolevn.me>2024-08-30 16:21:59 (GMT)
committerGitHub <noreply@github.com>2024-08-30 16:21:59 (GMT)
commite451a8937df95b2757b6def26b39aec1bd0f157f (patch)
tree1fbb6f2411aca9c212d205642925ca0c692165e4 /Lib/test/test_syntax.py
parentd8e69b2c1b3388c31a6083cfdd9dc9afff5b9860 (diff)
downloadcpython-e451a8937df95b2757b6def26b39aec1bd0f157f.zip
cpython-e451a8937df95b2757b6def26b39aec1bd0f157f.tar.gz
cpython-e451a8937df95b2757b6def26b39aec1bd0f157f.tar.bz2
gh-123440: Improve error message for `except as` used with not a name (#123442)
Diffstat (limited to 'Lib/test/test_syntax.py')
-rw-r--r--Lib/test/test_syntax.py47
1 files changed, 47 insertions, 0 deletions
diff --git a/Lib/test/test_syntax.py b/Lib/test/test_syntax.py
index 206b7f0..406ea21 100644
--- a/Lib/test/test_syntax.py
+++ b/Lib/test/test_syntax.py
@@ -1359,6 +1359,36 @@ Custom error message for try block mixing except and except*
Traceback (most recent call last):
SyntaxError: cannot have both 'except' and 'except*' on the same 'try'
+Better error message for using `except as` with not a name:
+
+ >>> try:
+ ... pass
+ ... except TypeError as obj.attr:
+ ... pass
+ Traceback (most recent call last):
+ SyntaxError: cannot use except statement with attribute
+
+ >>> try:
+ ... pass
+ ... except TypeError as obj[1]:
+ ... pass
+ Traceback (most recent call last):
+ SyntaxError: cannot use except statement with subscript
+
+ >>> try:
+ ... pass
+ ... except* TypeError as (obj, name):
+ ... pass
+ Traceback (most recent call last):
+ SyntaxError: cannot use except* statement with tuple
+
+ >>> try:
+ ... pass
+ ... except* TypeError as 1:
+ ... pass
+ Traceback (most recent call last):
+ SyntaxError: cannot use except* statement with literal
+
Ensure that early = are not matched by the parser as invalid comparisons
>>> f(2, 4, x=34); 1 $ 2
Traceback (most recent call last):
@@ -2770,6 +2800,23 @@ while 1:
with self.assertRaises(SyntaxError):
compile(source, "<string>", "exec")
+ def test_except_stmt_invalid_as_expr(self):
+ self._check_error(
+ textwrap.dedent(
+ """
+ try:
+ pass
+ except ValueError as obj.attr:
+ pass
+ """
+ ),
+ errtext="cannot use except statement with attribute",
+ lineno=4,
+ end_lineno=4,
+ offset=22,
+ end_offset=22 + len("obj.attr"),
+ )
+
def load_tests(loader, tests, pattern):
tests.addTest(doctest.DocTestSuite())