Skip to content

fix(docs): SIM107 'Use instead' example always returns -1 - #25494

Closed
avoronov-explyt wants to merge 1 commit into
astral-sh:mainfrom
avoronov-explyt:fix-sim107-docs
Closed

avoronov-explyt wants to merge 1 commit into
astral-sh:mainfrom
avoronov-explyt:fix-sim107-docs

Conversation

@avoronov-explyt

Copy link
Copy Markdown

Closes #22325.

The current "Use instead" example for SIM107 is misleading:

def squared(n):
    try:
        return_value = n**2
    except Exception:
        return_value = "An exception occurred"
    finally:
        return_value = -1
    return return_value

This always returns -1 because the finally block always executes and overwrites return_value, regardless of whether an exception occurred.

The fix replaces the example with two correct patterns:

  1. Simply return from try/except without a finally block
  2. Use finally only for cleanup that doesn't affect the return value

@astral-sh-bot
astral-sh-bot Bot requested a review from ntBre May 31, 2026 00:16
/// return "An exception occurred"
/// ```
///
/// Or, if cleanup is needed, use a `finally` block for cleanup only

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should extend our example with a cleanup logic instead. It seems rather uncommon to have a finally with just a return statement in it and it doesn't seem worthwhile to complicate the logic because of it.

To make the example less confusing overall, I suggest adding a second except handler that does not return.

@MichaReiser MichaReiser added the documentation Improvements or additions to public-facing documentation label Jun 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to public-facing documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SIM107 documentation example may be misleading

3 participants