Skip to content

_ as a keyword name in a class pattern raises a SyntaxError right after a positional pattern #163121

Todo

Description

@Robertboy18

Bug report

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):

match object():
    case C(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 :)

CPython versions tested on:

3.12, 3.15, CPython main branch

Operating systems tested on:

Linux

Linked PRs

Activity

  1. gvanrossum commented on Dec 3, 2026

    @gvanrossum
    Member

    Excellent catch! Looking forward to a PR. Please at-tag me so I will review it.

  2. added
    type-bug
    interpreter-core
    on Dec 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-coretopic-parsertype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions