-
-
Notifications
You must be signed in to change notification settings - Fork 33.2k
Description
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 syntaxTo make it much easier to immediately understand the problem and correct the pattern, I suggest we change Python.gram so that:
-
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! - ^^^ + ^^^^ -
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