gh-145239: Specialize match syntax error for unary addition in pattern#145658
gh-145239: Specialize match syntax error for unary addition in pattern#145658mvanhorn wants to merge 2 commits intopython:mainfrom
Conversation
…pattern Add a specialized syntax error message when unary '+' is used in match patterns. Instead of the generic "invalid syntax", users now see: "cannot use unary '+' in a literal pattern". This applies to all pattern contexts: top-level, alternatives, sequences, class patterns, and mapping patterns. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
|
Also @mvanhorn, Just a heads up, if you accept the |
|
Thanks for the heads up! |
|
No Problem, Happy to help let me know if you need help with anything else :) |
| def test_unary_add_in_literal_pattern(self): | ||
| self.assert_syntax_error(""" | ||
| match ...: | ||
| case +1: | ||
| pass | ||
| """) | ||
|
|
||
| def test_unary_add_in_or_pattern(self): | ||
| self.assert_syntax_error(""" | ||
| match ...: | ||
| case 1 | +2 | -3: | ||
| pass | ||
| """) | ||
|
|
||
| def test_unary_add_in_sequence_pattern(self): | ||
| self.assert_syntax_error(""" | ||
| match ...: | ||
| case [1, +2, -3]: | ||
| pass | ||
| """) | ||
|
|
||
| def test_unary_add_in_class_pattern(self): | ||
| self.assert_syntax_error(""" | ||
| match ...: | ||
| case Foo(x=+1, y=-2): | ||
| pass | ||
| """) | ||
|
|
||
| def test_unary_add_in_mapping_pattern(self): | ||
| self.assert_syntax_error(""" | ||
| match ...: | ||
| case {True: +1, False: -2}: | ||
| pass | ||
| """) | ||
|
|
There was a problem hiding this comment.
Occam's razor: we already test this in test_syntax where we additionally validate the exception message, so I'd remove any changes you made to test_patma.
There was a problem hiding this comment.
Good call - removed the test_patma changes in b07a507. The test_syntax coverage is sufficient.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
|
Thank you for taking the time to contribute. This syntax is now legal, so I'll have to close this. |
|
Thanks for the heads up, and for the review back in March. Good to know this is legal now. |
Fixes issue #145239.
Adds a specialized syntax error message when unary
+is used in match patterns. Instead of the generic "invalid syntax", users now see a clear message: "cannot use unary '+' in a literal pattern".This applies to all pattern contexts: top-level, alternatives, sequences, class patterns, and mapping patterns.
Changes
Grammar/python.gram: Addedinvalid_literal_patternrule that catches'+' NUMBERand raises the specialized errorParser/parser.c: Regenerated from grammarLib/test/test_syntax.py: Added doctest-style tests for all pattern contextsLib/test/test_patma.py: Added unit tests inTestSyntaxErrorsMisc/NEWS.d: Added NEWS entryExample
Before:
After:
This contribution was developed with AI assistance (Claude Code).
matchsyntax error for unary addition in pattern #145239