Skip to content

Commit 0b863b6

Browse files
Robertboy18miss-islington
authored andcommitted
gh-163121: Fix _= in a class pattern after a positional pattern (GH-163126)
(cherry picked from commit 81d9755) Co-authored-by: Robert Joseph <robujsph2001@gmail.com>
1 parent 458b722 commit 0b863b6

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
@@ -568,7 +568,7 @@ pattern_capture_target[expr_ty]:
568568
_PyPegen_set_expr_context(p, name, Store) }
569569

570570
wildcard_pattern[pattern_ty]:
571-
| "_" { _PyAST_MatchAs(NULL, NULL, EXTRA) }
571+
| "_" !'=' { _PyAST_MatchAs(NULL, NULL, EXTRA) }
572572

573573
value_pattern[pattern_ty]:
574574
| 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
@@ -2888,6 +2888,31 @@ class B(A): ...
28882888
h = 1
28892889
self.assertEqual(h, 1)
28902890

2891+
def test_patma_underscore_keyword_after_positional(self):
2892+
# gh-163121: "_" right after a positional pattern was parsed as a
2893+
# wildcard, so "_=" there was a SyntaxError.
2894+
class C:
2895+
__match_args__ = ("a",)
2896+
def __init__(self):
2897+
self.a = 1
2898+
self._ = 2
2899+
self.b = 3
2900+
2901+
match C():
2902+
case C(p, _=x, b=y):
2903+
z = 0
2904+
self.assertEqual((p, x, y, z), (1, 2, 3, 0))
2905+
match C():
2906+
case C(_, _=x):
2907+
z = 1
2908+
self.assertEqual((x, z), (2, 1))
2909+
match C():
2910+
case C(1, _=3):
2911+
z = 2
2912+
case C(1, _=2):
2913+
z = 3
2914+
self.assertEqual(z, 3)
2915+
28912916

28922917
class TestSyntaxErrors(unittest.TestCase):
28932918

‎Lib/test/test_syntax.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2287,6 +2287,12 @@
22872287
Traceback (most recent call last):
22882288
SyntaxError: positional patterns follow keyword patterns
22892289
2290+
>>> match ...:
2291+
... case Foo(a, _=1, x):
2292+
... ...
2293+
Traceback (most recent call last):
2294+
SyntaxError: positional patterns follow keyword patterns
2295+
22902296
>>> match ...:
22912297
... case Foo(z=1, x, y=2):
22922298
... ...
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)