[ruff] New rule unnecessary-if (RUF050)#24114
Conversation
ed8c2a2 to
4ed7067
Compare
This comment was marked as spam.
This comment was marked as spam.
4ed7067 to
9336a39
Compare
|
| code | total | + violation | - violation | + fix | - fix |
|---|---|---|---|---|---|
| RUF050 | 10 | 10 | 0 | 0 | 0 |
5c57d2b to
63f03f0
Compare
MichaReiser
left a comment
There was a problem hiding this comment.
Thank you. This overall looks great. I've only a few smaller comments
| # Trailing comment belonging to body | ||
| if True: | ||
| pass | ||
| # trailing comment |
There was a problem hiding this comment.
Can you add an example where the if is the only statement within a suite like what we see in https://github.com/pandas-dev/pandas/blob/389051d090579550f1a1259855f486d7f7e2159e/pandas/tests/generic/test_generic.py#L148
with pytest.raises(ValueError, match=msg):
if obj1:
passThere was a problem hiding this comment.
I've added, but this intentionally kind of "wrongly" (specifically for this case) results in:
with pytest.raises(ValueError, match=msg):
passPython's if statement calls obj1.__bool__() to evaluate the condition, and pandas overrides __bool__ on DataFrame to raise ValueError. That's what this check asserts (that you can't do if some_data_frame: checks in your code).
With RUF050 auto-fix this test will fail and I'm not sure what we can do about it (I've mentioned this in PR's description initially).
Shortly, in current implementation the situation is so:
- We strip
if Var: passentirely. - Side-effects like
if foo(): passresult infoo(). - But technically
if Var: passis actuallyif Var.__bool__(): pass, which has side-effect and logically must result inVar.__bool__(). But that's weird.
So we either should consider this limitation intended and expect users to set # noqa: RUF050 where they expect some side-effect from __bool__() (which is quite very edge case to be honest), or maybe make the whole rule unsafe.
There was a problem hiding this comment.
Let's mention this caveat in the documentation. This should be very uncommon and we can always change it if many users are running into this.
There was a problem hiding this comment.
Let me know when you updated the documentation so that we can merge this PR.
Skipping |
63f03f0 to
e6ddbd7
Compare
e6ddbd7 to
2af839c
Compare
9a62cdb to
b5dcd1e
Compare
* main: [ty] make `test-case` a dev-dependency (#24187) [ty] implement cycle normalization for more types to prevent too-many-cycle panics (#24061) [ty] Silence all diagnostics in unreachable code (#24179) [ty] Intern `InferableTypeVars` (#24161) Implement unnecessary-if (RUF050) (#24114) Recognize `Self` annotation and `self` assignment in SLF001 (#24144) Bump the npm version before publish (#24178) [ty] Disallow Self in metaclass and static methods (#23231) Use trusted publishing for NPM packages (#24171) [ty] Respect non-explicitly defined dataclass params (#24170) Add RUF072: warn when using operator on an f-string (#24162) [ty] Check return type of generator functions (#24026) Implement useless-finally (RUF-072) (#24165) [ty] Add test for a dataclass with a default field converter (#24169) [ty] Dataclass field converters (#23088) [flake8-bandit] Treat sys.executable as trusted input in S603 (#24106) [ty] Add support for `typing.Concatenate` (#23689) `ASYNC115`: autofix to use full qualified `anyio.lowlevel` import (#24166) [ty] Disallow read-only fields in TypedDict updates (#24128) Speed up diagnostic rendering (#24146)
ruff] New rule unnecessary-if (RUF050)
##### [\`v0.15.8\`](https://github.com/astral-sh/ruff/blob/HEAD/CHANGELOG.md#0158) Released on 2026-03-26. ##### Preview features - \[`ruff`] New rule `unnecessary-if` (`RUF050`) ([#24114](astral-sh/ruff#24114)) - \[`ruff`] New rule `useless-finally` (`RUF072`) ([#24165](astral-sh/ruff#24165)) - \[`ruff`] New rule `f-string-percent-format` (`RUF073`): warn when using `%` operator on an f-string ([#24162](astral-sh/ruff#24162)) - \[`pyflakes`] Recognize `frozendict` as a builtin for Python 3.15+ ([#24100](astral-sh/ruff#24100)) ##### Bug fixes - \[`flake8-async`] Use fully-qualified `anyio.lowlevel` import in autofix (`ASYNC115`) ([#24166](astral-sh/ruff#24166)) - \[`flake8-bandit`] Check tuple arguments for partial paths in `S607` ([#24080](astral-sh/ruff#24080)) - \[`pyflakes`] Skip `undefined-name` (`F821`) for conditionally deleted variables ([#24088](astral-sh/ruff#24088)) - `E501`/`W505`/formatter: Exclude nested pragma comments from line width calculation ([#24071](astral-sh/ruff#24071)) - Fix `%foo?` parsing in IPython assignment expressions ([#24152](astral-sh/ruff#24152)) - `analyze graph`: resolve string imports that reference attributes, not just modules ([#24058](astral-sh/ruff#24058)) ##### Rule changes - \[`eradicate`] ignore `ty: ignore` comments in `ERA001` ([#24192](astral-sh/ruff#24192)) - \[`flake8-bandit`] Treat `sys.executable` as trusted input in `S603` ([#24106](astral-sh/ruff#24106)) - \[`flake8-self`] Recognize `Self` annotation and `self` assignment in `SLF001` ([#24144](astral-sh/ruff#24144)) - \[`pyflakes`] `F507`: Fix false negative for non-tuple RHS in `%`-formatting ([#24142](astral-sh/ruff#24142)) - \[`refurb`] Parenthesize generator arguments in `FURB142` fixer ([#24200](astral-sh/ruff#24200)) ##### Performance - Speed up diagnostic rendering ([#24146](astral-sh/ruff#24146)) ##### Server - Warn when Markdown files are skipped due to preview being disabled ([#24150](astral-sh/ruff#24150)) ##### Documentation - Clarify `extend-ignore` and `extend-select` settings documentation ([#24064](astral-sh/ruff#24064)) - Mention AI policy in PR template ([#24198](astral-sh/ruff#24198)) ##### Other changes - Use trusted publishing for NPM packages ([#24171](astral-sh/ruff#24171)) ##### Contributors - [@bitloi](https://github.com/bitloi) - [@Sim-hu](https://github.com/Sim-hu) - [@mvanhorn](https://github.com/mvanhorn) - [@chinar-amrutkar](https://github.com/chinar-amrutkar) - [@markjm](https://github.com/markjm) - [@RenzoMXD](https://github.com/RenzoMXD) - [@vivekkhimani](https://github.com/vivekkhimani) - [@seroperson](https://github.com/seroperson) - [@moktamd](https://github.com/moktamd) - [@charliermarsh](https://github.com/charliermarsh) - [@ntBre](https://github.com/ntBre) - [@zanieb](https://github.com/zanieb) - [@dylwil3](https://github.com/dylwil3) - [@MichaReiser](https://github.com/MichaReiser) Renovate-Branch: renovate/2024.6-ruff-0.15.x Change-Id: Ifd4216a963962ffb24a4df69802bc60fcc29628d Priv-Id: 46d2f61be3a5e65a9fdd2fef998ba41ea3388f12
Summary
Implements the
unnecessary_ifrule (RUF050), which detects bareifstatements (noelif/else) where the body contains onlypassor...and the condition is side-effect-free.The rule complements RUF047 (
needless-else): when all branches of anif/elseare empty, RUF047 removes the emptyelseon the first fix pass, and RUF050 removes the remaining emptyifon the next pass.It also addresses #9472: when F401 removes unused imports from conditional blocks (e.g.,
if TYPE_CHECKINGorif sys.version_infoguards), the emptyifblocks left behind are cleaned up by RUF050, and the now-unused guard imports are then removed by F401 on subsequent fix iterations.TYPE_CHECKINGguards. Both TC005 and RUF050 triggers on emptyTYPE_CHECKINGguard and I'm unsure how to be with it. Maybe skipTYPE_CHECKINGguards in RUF050?__bool__-like blocks: https://github.com/pandas-dev/pandas/blob/389051d090579550f1a1259855f486d7f7e2159e/pandas/tests/generic/test_generic.py#L147-L150That's how
contains_effectworks and it seems a legit limitation, so I'm unsure how we should handle this (and should we at all). Should we make this fix unsafe because of this?Conditions with side effects (function calls,
await,yield, walrus operator) are skipped entirely, so the fix is always safe. If the body contains a comment (inline, own-line, or trailing), the rule also doesn't fire.Test Plan
RUF050.py- main rule test with error cases and non-error.unnecessary_if_and_needless_else- test function, which checks how RUF047 and RUF050 work together.unnecessary_if_and_unused_import- test function, which checks how F401 and RUF050 work together.Closes #9472
Closes #13929 ❓