Skip to content

Commit e398505

Browse files
committed
gh-162045: Imporve syntax error message for **_ in mapping patterns
1 parent 369d8bc commit e398505

5 files changed

Lines changed: 593 additions & 469 deletions

File tree

‎Grammar/invalid.gram‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,9 @@ invalid_mapping_pattern:
326326
| '{' (items_pattern ',')? rest=double_star_pattern ',' items_pattern ','? '}' { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
327327
rest,
328328
"double star pattern must be the last (right-most) subpattern in the mapping pattern") }
329+
| '{' (items_pattern ',')? '**' rest="_" (',' items_pattern)? ','? '}' { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
330+
rest,
331+
"double star pattern can't be named '_' in the mapping pattern") }
329332
invalid_class_argument_pattern[asdl_pattern_seq*]:
330333
| [positional_patterns ','] keyword_patterns ',' a=positional_patterns { a }
331334
invalid_if_stmt:

‎Lib/test/test_syntax.py‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,37 @@
374374
... case {**_}:
375375
... ...
376376
Traceback (most recent call last):
377-
SyntaxError: invalid syntax
377+
SyntaxError: double star pattern can't be named '_' in the mapping pattern
378+
379+
>>> match ...:
380+
... case {'a': a, **_}:
381+
... ...
382+
Traceback (most recent call last):
383+
SyntaxError: double star pattern can't be named '_' in the mapping pattern
384+
385+
>>> match ...:
386+
... case {'a': a, **_,}:
387+
... ...
388+
Traceback (most recent call last):
389+
SyntaxError: double star pattern can't be named '_' in the mapping pattern
390+
391+
>>> match ...:
392+
... case {**_, "spam": "eggs"}:
393+
... ...
394+
Traceback (most recent call last):
395+
SyntaxError: double star pattern can't be named '_' in the mapping pattern
396+
397+
>>> match ...:
398+
... case {"a": a, **_, "spam": "eggs"}:
399+
... ...
400+
Traceback (most recent call last):
401+
SyntaxError: double star pattern can't be named '_' in the mapping pattern
402+
403+
>>> match ...:
404+
... case {"a": a, **_, "spam": "eggs",}:
405+
... ...
406+
Traceback (most recent call last):
407+
SyntaxError: double star pattern can't be named '_' in the mapping pattern
378408
379409
# Check incorrect "case" placement with specialized error messages
380410
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improves :exc:`SyntaxError` message when using patterns like ``**_`` in
2+
mapping pattern matching.

0 commit comments

Comments
 (0)