Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Grammar/python.gram
Original file line number Diff line number Diff line change
Expand Up @@ -587,7 +587,7 @@ pattern_capture_target[expr_ty]:
_PyPegen_set_expr_context(p, name, Store) }

wildcard_pattern[pattern_ty]:
| "_" { _PyAST_MatchAs(NULL, NULL, EXTRA) }
| "_" !'=' { _PyAST_MatchAs(NULL, NULL, EXTRA) }

value_pattern[pattern_ty]:
| attr=attr !('.' | '(' | '=') { _PyAST_MatchValue(attr, EXTRA) }
Expand Down
25 changes: 25 additions & 0 deletions Lib/test/test_patma.py
Original file line number Diff line number Diff line change
Expand Up @@ -2979,6 +2979,31 @@ class B(A): ...
h = 1
self.assertEqual(h, 1)

def test_patma_underscore_keyword_after_positional(self):
# gh-163121: "_" right after a positional pattern was parsed as a
# wildcard, so "_=" there was a SyntaxError.
class C:
__match_args__ = ("a",)
def __init__(self):
self.a = 1
self._ = 2
self.b = 3

match C():
case C(p, _=x, b=y):
z = 0
self.assertEqual((p, x, y, z), (1, 2, 3, 0))
match C():
case C(_, _=x):
z = 1
self.assertEqual((x, z), (2, 1))
match C():
case C(1, _=3):
z = 2
case C(1, _=2):
z = 3
self.assertEqual(z, 3)


class TestSyntaxErrors(unittest.TestCase):

Expand Down
6 changes: 6 additions & 0 deletions Lib/test/test_syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -2373,6 +2373,12 @@
Traceback (most recent call last):
SyntaxError: positional patterns follow keyword patterns

>>> match ...:
... case Foo(a, _=1, x):
... ...
Traceback (most recent call last):
SyntaxError: positional patterns follow keyword patterns

>>> match ...:
... case Foo(z=1, x, y=2):
... ...
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix a :exc:`SyntaxError` when ``_`` is used as a keyword name in a class
pattern right after a positional pattern, as in ``case C(p, _=x):``.
12 changes: 7 additions & 5 deletions Parser/parser.c

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading