There's already a similar rule:
cpython/Grammar/python.gram
Line 1378 in 084e0f3
But, it has two problems:
My proposed change:
| or_pattern 'as' a=expression { RAISE_SYNTAX_ERROR_KNOWN_LOCATION( a, "cannot use pattern target as %s", _PyPegen_get_expr_name(a)) }
Why is it safe?
Here's how the parent rule is defined:
as_pattern[pattern_ty]: | pattern=or_pattern 'as' target=pattern_capture_target { _PyAST_MatchAs(pattern, target->v.Name.id, EXTRA) } | invalid_as_pattern
So, if pattern=or_pattern 'as' target=pattern_capture_target with a valid 'as' NAME is matched, we won't fall to the next invalid_ rule.
Proposed result:
>>> match 1: ... case x as a.b: ... ... File "<python-input-0>", line 2 case x as a.b: ... ^^^ SyntaxError: cannot use pattern target as attribute
Refs #123440
pythongh-123562: Improve `SyntaxError` message for `case ... as a.b`
Right, sorry, should have commented here too and not just on the PR. Imo it should be SyntaxError: cannot use attribute as pattern target
gh-123562: Improve `SyntaxError` message for `case ... as a.b` (#123563)
Thanks @sobolevn!
Activity
pythongh-123562: Improve `SyntaxError` message for `case ... as a.b`
cfbolz commented on Sep 2, 2024
Right, sorry, should have commented here too and not just on the PR. Imo it should be SyntaxError: cannot use attribute as pattern target
gh-123562: Improve `SyntaxError` message for `case ... as a.b` (#123563)
lysnikolaou commented on Sep 2, 2024
Thanks @sobolevn!