Skip to content

SIM107 documentation example may be misleading #22325

Open

Description

@ftnext

Question

I have a question about the example shown in the SIM107 (return-in-try-except-finally) documentation.
Could you clarify the intended purpose of this documentation example?

The current documentation includes this as good example:

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

Issue:

This code always returns -1 because the finally block overwrites the return_value variable.

print(squared(3))  # -1 not 9
print(squared("3"))  # -1 not "An exception occurred"

ref: https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions

If a finally clause is present, the finally clause will execute as the last task before the try statement completes.

Concern: Unclear purpose of the example

Version

ruff 0.14.10 (45bbb4c 2025-12-18)

Activity

  1. added
    question
    on Jan 1, 2026
  2. ntBre commented on Jan 1, 2026

    @ntBre
    Contributor

    Thanks for the report! I agree that this is confusing. I think the minimal change to get something that actually works is to remove only the return in the finally arm for the "Use instead" example:

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

    but even that is a bit confusing. Maybe a better initial example would be helpful.

  3. added
    documentation
    and removed
    question
    on Jan 1, 2026
  4. LoicRiegel commented on Jan 3, 2026

    @LoicRiegel
    Contributor

    I thought for a while and searched online, and I could not find a good example. The best one to me is the one from the issue @ftnext linked (MartinThoma/flake8-simplify#9).
    I'm so surprised that this rule is in the flake8-simplify linter. This is not about simplifing code, returning in a finally block is never what we want!!

  5. added a commit that references this issue on Jun 16, 2026
    359f1fe
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

    documentation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions