Skip to content

PLR5501 and PLW0120 safe fixes delete a trailing comment on the else: line #29395

Closed

Description

@briksdaal

Summary

The safe fixes for collapsible-else-if (PLR5501) and useless-else-on-loop (PLW0120) delete a comment that
trails the else: they remove. The superfluous-else-* fixes (RET505–RET508) keep such a comment and move it to
its own line.

def f(a, b):
    if a:
        return 1
    else:  # explain the fallback
        if b:
            return 2
        else:
            return 3

ruff check --isolated --select PLR5501 --fix repro.py:

def f(a, b):
    if a:
        return 1
    elif b:
        return 2
    else:
        return 3
def f(xs):
    for x in xs:
        if x:
            return x
    else:  # nothing found
        return None

ruff check --isolated --select PLW0120 --fix repro.py:

def f(xs):
    for x in xs:
        if x:
            return x
    return None

For comparison, ruff check --isolated --select RET505 --fix on

def f(a):
    if a:
        return 1
    else:  # the fallback
        return 2

keeps the comment:

def f(a):
    if a:
        return 1
    # the fallback
    return 2

remove_else in flake8_return/rules/function.rs handles this explicitly ("if there is a comment on the same line as
the Colon, let's keep it"). convert_to_elif (PLR5501) and remove_else in useless_else_on_loop.rs (PLW0120)
replace from the start of the else line and keep only what follows that line. #9779 and #13545 fixed own-line comments
between else: and the nested if; those are kept now, but a comment on the else: line itself is not.

Real-world cases: pydantic 2.14.1, pydantic/deprecated/json.py lines 109 and 132
(else: # We have exited the for loop without finding a suitable encoder), and contourpy 1.4.0,
tests/util_config.py line 445 (else: # !quad_as_tri).

(Found while running Ruff's safe fixes over the top PyPI packages.)

Version

ruff 0.17.0

Activity

  1. added
    bugAn issue describing something that isn't working, or a PR that fixes a bug
    on Oct 14, 2026
  2. added a commit that references this issue on Oct 16, 2026
    8d122c1
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

    bugAn issue describing something that isn't working, or a PR that fixes a bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions