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

TRY300: Recommend putting code after the try/except instead of inside a else #13885

Open
cbornet opened this issue Oct 23, 2024 · 1 comment
Open
Labels
fixes Related to suggested fixes for violations

Comments

@cbornet
Copy link

cbornet commented Oct 23, 2024

When an exception handler re-raises or returns, it seems to me that it's better to put the "else" code as a follow-up to the try/except than in a "else".

Eg for the code

import logging


def reciprocal(n):
    try:
        rec = 1 / n
        print(f"reciprocal of {n} is {rec}")
        return rec
    except ZeroDivisionError:
        logging.exception("Exception occurred")
        raise

you get TRY300 Consider moving this statement to an else block
but the best for me would be to write:

import logging


def reciprocal(n):
    try:
        rec = 1 / n
    except ZeroDivisionError:
        logging.exception("Exception occurred")
        raise
    print(f"reciprocal of {n} is {rec}")
    return rec

BTW, the current example also seems incorrect as reciprocal returns an implicit None (See RET503 even though it doesn't detect it)

@MichaReiser MichaReiser added the fixes Related to suggested fixes for violations label Oct 23, 2024
@MichaReiser
Copy link
Member

I think that makes sense. But we have to be careful only to do so if all except branches re-raise and there's no existing else branch.

Moving the code after the try would change the semantic in this case.

def reciprocal(n):
    try:
        rec = 1 / n
        print(f"reciprocal of {n} is {rec}")
        return rec
    except ZeroDivisionError:
        logging.exception("Exception occurred")
        raise

    except Other:
        logging.exception("Exception occurred")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
fixes Related to suggested fixes for violations
Projects
None yet
Development

No branches or pull requests

2 participants