Skip to content

[python-package]Add superfluous-else-raise (RET506) rule to detect unnecessary else after raise #6903

@suk1yak1

Description

@suk1yak1

Summary

Introduce a new linting rule superfluous-else-raise (RET506) to Ruff. This rule would flag unnecessary else blocks following a raise statement, encouraging cleaner and more readable code.

Motivation

In Python, after a raise statement, the control flow is interrupted, making an else block redundant and potentially misleading. Detecting and eliminating such superfluous else blocks improves code clarity and aligns with Python best practices. Adding this rule to Ruff would help developers maintain a more idiomatic code style automatically.

Description

While working on a pull request for the LightGBM project, a reviewer pointed out an unnecessary else block following a raise statement (reference). This feedback highlighted the importance of avoiding superfluous else clauses after control flow interruptions like raise. Detecting and eliminating such redundant code improves readability and aligns with Python best practices. Adding this rule to Ruff would help developers automatically catch and fix this pattern, leading to cleaner and more idiomatic Python code.

For example, the following code:

if condition:
    raise ValueError("Invalid value")
else:
    do_something()

should be refactored to:

if condition:
    raise ValueError("Invalid value")
do_something()

References

PEP 8 – Programming Recommendations (avoid unnecessary nesting)
ruff rules - return ruleset (for existing similar patterns like RET505, RET507)
LightGBM PR #6892 reviewer comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions