Skip to content

Incorrect SyntaxError location for walrus operator in multi-line conditional expression #146260

@zrekryu

Description

@zrekryu

Bug report

Bug description:

When using the walrus operator (:=) inside a multi-line conditional expression, Python raises a SyntaxError with the error position pointing to the wrong location.
The caret (^) is shown under the expression body instead of the if clause where the syntax issue actually occurs, making debugging misleading.
The error indicator should instead highlight the if portion (or walrus usage context), not the preceding expression line.

Code

(
    1
    if x := True
    else 2
)

Traceback

File "[REDACTED]", line 2
    1
    ^
SyntaxError: expected 'else' after 'if' expression

It locates error to 1 but it should have located to if x := True (line no. 3)

It does not errors when condition is parenthesized:

(
    1
    if (x := True)
    else 2
)  # output: 1

CPython versions tested on:

3.14

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)topic-parsertype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions