Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Special syntax error for elif after else #129858

Open
swfarnsworth opened this issue Feb 8, 2025 · 1 comment
Open

Special syntax error for elif after else #129858

swfarnsworth opened this issue Feb 8, 2025 · 1 comment
Labels
interpreter-core (Objects, Python, Grammar, and Parser dirs) topic-parser type-feature A feature request or enhancement

Comments

@swfarnsworth
Copy link
Contributor

swfarnsworth commented Feb 8, 2025

Feature or enhancement

Proposal:

I've implemented a special syntax error in the case that an elif follows an else. See here.

if i % 3 == 0:
    print("divisible by 3")
else:
    print("not divisible by 3")
elif i % 2 == 0:
    print("divisible by 2")
# SyntaxError: elif not allowed after else

This is currently the extent of the new behavior. If possible, I would be interested to implement behavior like this:

if isinstance(i, int):
    if i % 3 == 0:
        print("divisible by 3")
    else:
        print("not divisible by 3")
    elif isinstance(i, str):
        print("i is a string")
# SyntaxError: elif not allowed after else. Perhaps the elif is at the wrong indentation level?

This would be even more informative for beginners, but I'm not sure if the parser supports that level of state. In particular, we wouldn't want the latter syntax error (the one that suggests that the indentation level is wrong) to be raised if the invalid elif were within a for block.

Has this already been discussed elsewhere?

No response given

Links to previous discussion of this feature:

No response

Linked PRs

@swfarnsworth swfarnsworth added the type-feature A feature request or enhancement label Feb 8, 2025
@sobolevn
Copy link
Member

sobolevn commented Feb 9, 2025

I like the new error message! But, looks like Perhaps the elif is at the wrong indentation level? part would be really hard to generate, if even possible.

Please, send a PR with the first message for now :)

@picnixz picnixz added the interpreter-core (Objects, Python, Grammar, and Parser dirs) label Feb 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
interpreter-core (Objects, Python, Grammar, and Parser dirs) topic-parser type-feature A feature request or enhancement
Projects
None yet
Development

No branches or pull requests

3 participants