Skip to content

Commit f59b4ec

Browse files
committed
gh-138864: Improve SyntaxError message for case with expression
1 parent 805e336 commit f59b4ec

File tree

4 files changed

+293
-201
lines changed

4 files changed

+293
-201
lines changed

Grammar/python.gram

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,7 @@ case_block[match_case_ty]:
495495
| invalid_case_block
496496
| "case" pattern=patterns guard=guard? ':' body=block {
497497
_PyAST_match_case(pattern, guard, body, p->arena) }
498+
| invalid_case_pattern
498499

499500
guard[expr_ty]: 'if' guard=named_expression { guard }
500501

@@ -1480,6 +1481,10 @@ invalid_case_block:
14801481
| "case" patterns guard? NEWLINE { RAISE_SYNTAX_ERROR("expected ':'") }
14811482
| a="case" patterns guard? ':' NEWLINE !INDENT {
14821483
RAISE_INDENTATION_ERROR("expected an indented block after 'case' statement on line %d", a->lineno) }
1484+
invalid_case_pattern:
1485+
| "case" a=expression guard? ':' block {
1486+
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
1487+
a, "cannot use case statement with %s", _PyPegen_get_expr_name(a)) }
14831488
invalid_as_pattern:
14841489
| or_pattern 'as' a="_" { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot use '_' as a target") }
14851490
| or_pattern 'as' a=expression {

Lib/test/test_syntax.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -374,13 +374,18 @@
374374
... case {**rest, "key": value}:
375375
... ...
376376
Traceback (most recent call last):
377-
SyntaxError: invalid syntax
377+
SyntaxError: cannot use case statement with dict literal
378378
379379
>>> match ...:
380380
... case {**_}:
381381
... ...
382382
Traceback (most recent call last):
383-
SyntaxError: invalid syntax
383+
SyntaxError: cannot use case statement with dict literal
384+
385+
>>> match ...:
386+
... case ...: ...
387+
Traceback (most recent call last):
388+
SyntaxError: cannot use case statement with ellipsis
384389
385390
# But prefixes of soft keywords should
386391
# still raise specialized errors
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve :exc:`SyntaxError` message for using ``case`` with regular
2+
expressions.

0 commit comments

Comments
 (0)