KEMBAR78
Improve the syntax error from an ill-positioned double-star subpattern · Issue #140253 · python/cpython · GitHub
Skip to content

Improve the syntax error from an ill-positioned double-star subpattern #140253

@bswck

Description

@bswck

Feature or enhancement

Proposal:

In the section on mapping patterns in match/case, it is documented that double-star subpatterns can only exist as the right-most subpattern of the enclosing mapping pattern:

The double star pattern must be the last subpattern in the mapping pattern.

This rule is not quite obvious -- it's easy to break it by accident (I did :-)).
This is the syntax error that's currently reported if the rule is violated:

❯ ./python -q
>>> match d := {"a": 1, "b": 2, "c": 3}:
...     case {"a": a, "b": b, "c": c}:  # fine
...         print(d)
...         
{'a': 1, 'b': 2, 'c': 3}
>>> match d := {"a": 1, "b": 2, "c": 3}:
...     case {"a": a, "b": b, **rest}:  # **rest is last -- fine
...         print(d, rest)
...         
{'a': 1, 'b': 2, 'c': 3} {'c': 3}
>>> match d := {"a": 1, "b": 2, "c": 3}:
...     case {"a": a, **rest, "b": b}:  # **rest is not last -- wrong!
...         print(d, rest)
...         
  File "<python-input-2>", line 2
    case {"a": a, **rest, "b": b}:  # **rest is not last -- wrong!
                          ^^^
SyntaxError: invalid syntax
>>> match d := {"a": 1, "b": 2, "c": 3}:
...     case {**rest, "a": a, "b": b}:  # **rest is not last -- wrong!
...         print(d, rest)
...         
  File "<python-input-3>", line 2
    case {**rest, "a": a, "b": b}:  # **rest is not last -- wrong!
                  ^^^
SyntaxError: invalid syntax

To make it much easier to immediately understand the problem and correct the pattern, I suggest we change Python.gram so that:

  1. the offset is placed on the faulty double star subpattern:

    case {"a": a, **rest, "b": b}:  # **rest is not last -- wrong!
    -                     ^^^
    +               ^^^^
    case {**rest, "a": a, "b": b}:  # **rest is not last -- wrong!
    -             ^^^
    +       ^^^^
  2. the error message reads that the double-star pattern has to be the right-most subpattern, e.g.:

    SyntaxError: double star pattern must be the last (right-most) subpattern in the mapping pattern

CC @pablogsal @sobolevn @ZeroIntensity

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions