Skip to content

Confusing SyntaxError message for x for x if range(1) #111488

@sobolevn

Description

@sobolevn

Bug report

Today I made a typo: instead of in I wrote if.
I was quite interested to see the error message:

>>> [x for x if range(1)]
  File "<stdin>", line 1
    [x for x if range(1)]
           ^^^^^^^^^^^^^
SyntaxError: expected 'else' after 'if' expression

I don't think that this error message is correct. Why? Because even if we follow the rabbit hole and use else, we won't be ever correct:

>>> [x for (x if range(1) else y) in range(1)]
  File "<stdin>", line 1
    [x for (x if range(1) else y) in range(1)]
            ^^^^^^^^^^^^^^^^^^^^
SyntaxError: cannot assign to conditional expression

So, maybe we should change it to be something like:

>>> [x for x if range(1)]
  File "<stdin>", line 1
    [x for x if range(1)]
             ^^
SyntaxError: expected 'in', got 'if'

Suggestions about wording are welcome :)

If others agree, I would like to work on this.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.11only security fixes3.12only security fixes3.13bugs and security fixesinterpreter-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