Skip to content
Open
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
3 changes: 3 additions & 0 deletions Grammar/python.gram
Original file line number Diff line number Diff line change
Expand Up @@ -536,6 +536,7 @@ literal_pattern[pattern_ty]:
| 'None' { _PyAST_MatchSingleton(Py_None, EXTRA) }
| 'True' { _PyAST_MatchSingleton(Py_True, EXTRA) }
| 'False' { _PyAST_MatchSingleton(Py_False, EXTRA) }
| invalid_literal_pattern

# Literal expressions are used to restrict permitted mapping pattern keys
literal_expr[expr_ty]:
Expand Down Expand Up @@ -1519,6 +1520,8 @@ invalid_mapping_pattern:
"double star pattern must be the last (right-most) subpattern in the mapping pattern") }
invalid_class_argument_pattern[asdl_pattern_seq*]:
| [positional_patterns ','] keyword_patterns ',' a=positional_patterns { a }
invalid_literal_pattern:
| a='+' NUMBER { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot use unary '+' in a literal pattern") }
invalid_if_stmt:
| 'if' named_expression NEWLINE { RAISE_SYNTAX_ERROR("expected ':'") }
| a='if' a=named_expression ':' NEWLINE !INDENT {
Expand Down
32 changes: 32 additions & 0 deletions Lib/test/test_syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -2399,6 +2399,38 @@
Traceback (most recent call last):
SyntaxError: double star pattern must be the last (right-most) subpattern in the mapping pattern

Unary '+' is not allowed in match patterns:

>>> match ...:
... case +1:
... ...
Traceback (most recent call last):
SyntaxError: cannot use unary '+' in a literal pattern

>>> match ...:
... case 1 | +2 | -3:
... ...
Traceback (most recent call last):
SyntaxError: cannot use unary '+' in a literal pattern

>>> match ...:
... case [1, +2, -3]:
... ...
Traceback (most recent call last):
SyntaxError: cannot use unary '+' in a literal pattern

>>> match ...:
... case Foo(x=+1, y=-2):
... ...
Traceback (most recent call last):
SyntaxError: cannot use unary '+' in a literal pattern

>>> match ...:
... case {True: +1, False: -2}:
... ...
Traceback (most recent call last):
SyntaxError: cannot use unary '+' in a literal pattern

Uses of the star operator which should fail:

A[:*b]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Improved the error message when using unary ``+`` in a :keyword:`match`
pattern. Instead of a generic "invalid syntax", Python now reports "cannot
use unary '+' in a literal pattern".
Loading
Loading