Skip to content

Special syntax error for elif after else #129858

Closed
@swfarnsworth

Description

@swfarnsworth

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

Activity

sobolevn

sobolevn commented on Feb 9, 2025

@sobolevn
Member

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 :)

added a commit that references this issue on Apr 25, 2025

gh-129858: Special syntax error for `elif` block after `else` (#129902)

99b71ef
StanFromIreland

StanFromIreland commented on May 10, 2025

@StanFromIreland
Contributor

if even possible.

The first part was merged, is it time to close this?

swfarnsworth

swfarnsworth commented on May 15, 2025

@swfarnsworth
ContributorAuthor

I just spoke to @pablogsal about the stateful behaviour, and he confirmed that it's not possible; the behavior that is possible is already merged, so we can close this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Special syntax error for `elif` after `else` · Issue #129858 · python/cpython

      Follow Lee on X/Twitter - Father, Husband, Serial builder creating AI, crypto, games & web tools. We are friends :) AI Will Come To Life!

      Check out: eBank.nz (Art Generator) | Netwrck.com (AI Tools) | Text-Generator.io (AI API) | BitBank.nz (Crypto AI) | ReadingTime (Kids Reading) | RewordGame | BigMultiplayerChess | WebFiddle | How.nz | Helix AI Assistant