Skip to content

Commit 81d9755

Browse files
authored
gh-163121: Fix _= in a class pattern after a positional pattern (#163126)
1 parent 065c6aa commit 81d9755

5 files changed

Lines changed: 41 additions & 6 deletions

File tree

‎Grammar/python.gram‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -580,7 +580,7 @@ pattern_capture_target[expr_ty]:
580580
_PyPegen_set_expr_context(p, name, Store) }
581581

582582
wildcard_pattern[pattern_ty]:
583-
| "_" { _PyAST_MatchAs(NULL, NULL, EXTRA) }
583+
| "_" !'=' { _PyAST_MatchAs(NULL, NULL, EXTRA) }
584584

585585
value_pattern[pattern_ty]:
586586
| attr=attr !('.' | '(' | '=') { _PyAST_MatchValue(attr, EXTRA) }

‎Lib/test/test_patma.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2979,6 +2979,31 @@ class B(A): ...
29792979
h = 1
29802980
self.assertEqual(h, 1)
29812981

2982+
def test_patma_underscore_keyword_after_positional(self):
2983+
# gh-163121: "_" right after a positional pattern was parsed as a
2984+
# wildcard, so "_=" there was a SyntaxError.
2985+
class C:
2986+
__match_args__ = ("a",)
2987+
def __init__(self):
2988+
self.a = 1
2989+
self._ = 2
2990+
self.b = 3
2991+
2992+
match C():
2993+
case C(p, _=x, b=y):
2994+
z = 0
2995+
self.assertEqual((p, x, y, z), (1, 2, 3, 0))
2996+
match C():
2997+
case C(_, _=x):
2998+
z = 1
2999+
self.assertEqual((x, z), (2, 1))
3000+
match C():
3001+
case C(1, _=3):
3002+
z = 2
3003+
case C(1, _=2):
3004+
z = 3
3005+
self.assertEqual(z, 3)
3006+
29823007

29833008
class TestSyntaxErrors(unittest.TestCase):
29843009

‎Lib/test/test_syntax.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2433,6 +2433,12 @@
24332433
Traceback (most recent call last):
24342434
SyntaxError: positional patterns follow keyword patterns
24352435
2436+
>>> match ...:
2437+
... case Foo(a, _=1, x):
2438+
... ...
2439+
Traceback (most recent call last):
2440+
SyntaxError: positional patterns follow keyword patterns
2441+
24362442
>>> match ...:
24372443
... case Foo(z=1, x, y=2):
24382444
... ...
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a :exc:`SyntaxError` when ``_`` is used as a keyword name in a class
2+
pattern right after a positional pattern, as in ``case C(p, _=x):``.

‎Parser/parser.c‎

Lines changed: 7 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)