Improve SyntaxError message for `match`

Currently, Python raises:

SyntaxError: invalid syntax. Did you mean 'with'?

for switch foo:. This is confusing and irrelevant, because in many other programming languages, switch is a reserved keyword that serves exact the same function as Python’s match.

Thus, users typing switch almost certainly intended to use match, mistakenly substituting the keyword from other languages, rather than meaning to write a with statement.

Therefore, I believe it’s better to raise:

SyntaxError: invalid syntax. Did you mean 'match'?

in this case.

Additionally, code with typos like mach foo: or matc foo: currently lacks a keyword typo suggestion.

8 Likes

I think the issue is that switch is really close to with. Would probably be worth special casing for sure.

1 Like

If there is already special casing (I don’t know), this would be worth adding. There may have been a discussion of this already on discuss or cpython issues. Perhaps you can search.

1 Like

Just to play devil’s advocate (I’m +0 on the idea), the switch statement in other languages is usually closer to a Pythonif-else statement with equality conditions:

# switch x:
#    case 1:
#      ...
#    case 2:
#      ...
#    otherwise:
#      ...
if x == 1:
    ...
elif x == 2:
    ...
else:
    ...

If that’s what you were going to use match for, I would be leery of encouraging it. If that’s not what you mean to use match for, then you are unlikely to be confusing match with switch or needing much of a hint to use the correct keyword.

3 Likes

I agree that match and switch are very different. But if someone types switch foo:, they did not mean with foo:. True, they might likely need to adjust their understanding because of the difference between match and switch. But I don’t think suggesting match is “encouraging” an incorrect use. It’s helping them over a small speed bump on their way to a larger learning.

12 Likes

When originally learning Python, I assumed a switch statement existed, so I think the error message might be useful. Also, the distance between “switch” and “width” does not suggest a typo, but rather a lack of knowledge of the keyword, then again proving it useful.

I’m guessing it’s a generic “are you within edit distance 2 of a keyword”, and switch is indeed within 2 edits of with.

1 Like

There is special casing for attributes, so I guess that it would not be out of line to have a special case for keywords.

Open an issue.

I have already created one at Improve SyntaxError message for `match` · Issue #151128 · python/cpython · GitHub

1 Like