You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
_ as a keyword name in a class pattern raises a SyntaxError right after a positional pattern #163121
While working on a Lean formalization of the Python specification, we came across an inconsistency in how _ is handled as a keyword name in class patterns.
The following raises a SyntaxError on 3.12.16, 3.15.2 and main (9d6fa5d):
matchobject():
caseC(p, _=x, attr=y):
pass
File "repro.py", line 2
case C(p, _=x, attr=y):
^
SyntaxError: invalid syntax
However, both case C(p, attr=y, _=x): and case C(_=x, attr=y): compile without any issues. Given that the grammar defines keyword_pattern as NAME '=' pattern, I would expect all three to be valid.
I think the issue is in Grammar/python.gram. Both pattern_capture_target and value_pattern have a !('.' | '(' | '=') lookahead, whereas wildcard_pattern is just "_". This seems to cause positional_patterns to consume p, _ before failing at the =.
Adding !'=' to wildcard_pattern and regenerating the parser fixes the issue locally (on main at 8dc1ea9), and all 535 tests across test_patma, test_grammar and test_syntax pass on the patched build.
Thanks to @MichaReiser for spotting this while looking at astral-sh/ruff#31300. Happy to open a PR with the fix and a regression test :)
Activity
gvanrossum commentedon Dec 3, 2026
Excellent catch! Looking forward to a PR. Please at-tag me so I will review it.