Skip to content

Commit 0507303

Browse files
authored
bpo-44368: Improve syntax errors with invalid as pattern targets (GH-26632)
1 parent e7b4644 commit 0507303

File tree

4 files changed

+332
-213
lines changed

4 files changed

+332
-213
lines changed

Grammar/python.gram

+4
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,7 @@ pattern[pattern_ty]:
244244
as_pattern[pattern_ty]:
245245
| pattern=or_pattern 'as' target=pattern_capture_target {
246246
_PyAST_MatchAs(pattern, target->v.Name.id, EXTRA) }
247+
| invalid_as_pattern
247248
or_pattern[pattern_ty]:
248249
| patterns[asdl_pattern_seq*]='|'.closed_pattern+ {
249250
asdl_seq_LEN(patterns) == 1 ? asdl_seq_GET(patterns, 0) : _PyAST_MatchOr(patterns, EXTRA) }
@@ -974,6 +975,9 @@ invalid_case_block:
974975
| "case" patterns guard? !':' { RAISE_SYNTAX_ERROR("expected ':'") }
975976
| a="case" patterns guard? ':' NEWLINE !INDENT {
976977
RAISE_INDENTATION_ERROR("expected an indented block after 'case' statement on line %d", a->lineno) }
978+
invalid_as_pattern:
979+
| or_pattern 'as' a="_" { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot use '_' as a target") }
980+
| or_pattern 'as' !NAME a=expression { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "invalid pattern target") }
977981
invalid_if_stmt:
978982
| 'if' named_expression NEWLINE { RAISE_SYNTAX_ERROR("expected ':'") }
979983
| a='if' a=named_expression ':' NEWLINE !INDENT {

Lib/test/test_syntax.py

+14
Original file line numberDiff line numberDiff line change
@@ -1226,6 +1226,20 @@
12261226
>>> import ä £
12271227
Traceback (most recent call last):
12281228
SyntaxError: invalid character '£' (U+00A3)
1229+
1230+
Invalid pattern matching constructs:
1231+
1232+
>>> match ...:
1233+
... case 42 as _:
1234+
... ...
1235+
Traceback (most recent call last):
1236+
SyntaxError: cannot use '_' as a target
1237+
1238+
>>> match ...:
1239+
... case 42 as 1+2+4:
1240+
... ...
1241+
Traceback (most recent call last):
1242+
SyntaxError: invalid pattern target
12291243
"""
12301244

12311245
import re
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Improve syntax errors for invalid "as" targets. Patch by Pablo Galindo

0 commit comments

Comments
 (0)