-
Notifications
You must be signed in to change notification settings - Fork 4k
Description
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