Search code examples
pythonpython-3.xconditional-operatorpython-assignment-expression

On this Conditional Expression, what the syntax error about?


I get:

  return r.group() if r := re.match(rx,l) else None
                      ^

SyntaxError: invalid syntax

whereas

        return r.group() if (r := re.match(rx,l)) else None

is accepted.

What is invalid about the first's syntax? And what other interpretation of it is there, than the second, such that it is not unambiguous?


Solution

  • Limiting the valid places in which the walrus operator ("assignment expression" for those who have killed their inner child) can be used was a mostly elective thing. They didn't want it replacing = for assignment, or getting used constantly to condense multiple lines of code down to one for the fun of it, so they put limitations on its syntax that make it awkward outside of the cases it was really designed for. The biggest limitation was that they require parentheses in cases they didn't strictly need to (e.g. the most obvious case is that the language could trivially have implemented it such that x := 1 by itself worked, but chose not to do so).

    The language's grammar spec describes the precise rules (emphasis added):

    Assignment expressions must be surrounded by parentheses when used as expression statements and when used as sub-expressions in slicing, conditional, lambda, keyword-argument, and comprehension-if expressions and in assert, with, and assignment statements. In all other places where they can be used, parentheses are not required, including in if and while statements.

    Basically, unparenthesized walruses are definitionally incompatible with conditional expressions, because the Python language designers said so.