Unary Plus is Allowed in Match Patterns in Python 3.15

Unary Plus is Allowed in Match Patterns in Python 3.15

A match statement can compare a value against number literals, and negative numbers have always been accepted, so case -1: is valid. A leading plus sign was not. Writing case +1: was rejected by the parser, even though the two signs are equally natural to write when a match deals with signed values.

For example, a function describing a movement step handles three cases:

def describe(step):
    match step:
        case -1:
            return 'left'
        case +1:
            return 'right'
        case 0:
            return 'stay'


print(describe(-1))

Before Python 3.15:

  File "main.py", line 5
    case +1:
         ^
SyntaxError: invalid syntax

The file does not run at all. The error is raised while parsing, so it appears before any of the function is executed.

Since Python 3.15:

left

The restriction has been removed and the same source now parses. Nothing about the behaviour changed. The value +1 is the value 1, so the two patterns match exactly the same input. Writing +1 next to -1 keeps the cases aligned.

Leave a Comment

Cancel reply

Your email address will not be published.