Skip to content

Commit 0acc258

Browse files
authored
bpo-44456: Improve the syntax error when mixing keyword and positional patterns (GH-26793)
1 parent b19f455 commit 0acc258

File tree

6 files changed

+672
-464
lines changed

6 files changed

+672
-464
lines changed

Grammar/python.gram

+8
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,7 @@ class_pattern[pattern_ty]:
380380
CHECK(asdl_expr_seq*, _PyPegen_get_pattern_keys(p, keywords)))),
381381
CHECK(asdl_pattern_seq*, _PyPegen_get_patterns(p, keywords)),
382382
EXTRA) }
383+
| invalid_class_pattern
383384
positional_patterns[asdl_pattern_seq*]:
384385
| args[asdl_pattern_seq*]=','.pattern+ { args }
385386
keyword_patterns[asdl_seq*]:
@@ -978,6 +979,13 @@ invalid_case_block:
978979
invalid_as_pattern:
979980
| or_pattern 'as' a="_" { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot use '_' as a target") }
980981
| or_pattern 'as' !NAME a=expression { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "invalid pattern target") }
982+
invalid_class_pattern:
983+
| name_or_attr '(' a=invalid_class_argument_pattern { RAISE_SYNTAX_ERROR_KNOWN_RANGE(
984+
PyPegen_first_item(a, pattern_ty),
985+
PyPegen_last_item(a, pattern_ty),
986+
"positional patterns follow keyword patterns") }
987+
invalid_class_argument_pattern[asdl_pattern_seq*]:
988+
| [positional_patterns ','] keyword_patterns ',' a=positional_patterns { a }
981989
invalid_if_stmt:
982990
| 'if' named_expression NEWLINE { RAISE_SYNTAX_ERROR("expected ':'") }
983991
| a='if' a=named_expression ':' NEWLINE !INDENT {

Lib/test/test_syntax.py

+24
Original file line numberDiff line numberDiff line change
@@ -1240,6 +1240,30 @@
12401240
... ...
12411241
Traceback (most recent call last):
12421242
SyntaxError: invalid pattern target
1243+
1244+
>>> match ...:
1245+
... case Foo(z=1, y=2, x):
1246+
... ...
1247+
Traceback (most recent call last):
1248+
SyntaxError: positional patterns follow keyword patterns
1249+
1250+
>>> match ...:
1251+
... case Foo(a, z=1, y=2, x):
1252+
... ...
1253+
Traceback (most recent call last):
1254+
SyntaxError: positional patterns follow keyword patterns
1255+
1256+
>>> match ...:
1257+
... case Foo(z=1, x, y=2):
1258+
... ...
1259+
Traceback (most recent call last):
1260+
SyntaxError: positional patterns follow keyword patterns
1261+
1262+
>>> match ...:
1263+
... case C(a=b, c, d=e, f, g=h, i, j=k, ...):
1264+
... ...
1265+
Traceback (most recent call last):
1266+
SyntaxError: positional patterns follow keyword patterns
12431267
"""
12441268

12451269
import re
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve the syntax error when mixing positional and keyword patterns. Patch
2+
by Pablo Galindo.

0 commit comments

Comments
 (0)