[ruff] Unnecessary cast to int (RUF046)#14697
Conversation
|
Maybe this should be expanded to cover those suggested in #14292 as well, in which case the rule should be renamed to |
|
| code | total | + violation | - violation | + fix | - fix |
|---|---|---|---|---|---|
| RUF046 | 15 | 15 | 0 | 0 | 0 |
Formatter (stable)
✅ ecosystem check detected no format changes.
Formatter (preview)
✅ ecosystem check detected no format changes.
|
+1 unnecessary cast to int. This is more future proof: when type inference is available unnecessary int casts could be detected for a much wider class of functions. Consider expanding this rule to other builtin functions such as “len”. Edit: indeed as suggested in the other issue. |
MichaReiser
left a comment
There was a problem hiding this comment.
I like your proposal to use the more generic name unnecessary-cast-to-int.
crates/ruff_linter/src/rules/ruff/rules/unnecessary_round_cast.rs
Outdated
Show resolved
Hide resolved
ruff] Unnecessary round() cast (RUF046)ruff] Unnecessary cast to int (RUF046)
crates/ruff_linter/src/rules/ruff/rules/unnecessary_cast_to_int.rs
Outdated
Show resolved
Hide resolved
MichaReiser
left a comment
There was a problem hiding this comment.
Thanks.
The special casing where ndigitis=0 is incorrect. We should not flag that usage.
crates/ruff_linter/src/rules/ruff/rules/unnecessary_cast_to_int.rs
Outdated
Show resolved
Hide resolved
crates/ruff_linter/src/rules/ruff/rules/unnecessary_cast_to_int.rs
Outdated
Show resolved
Hide resolved
Just FYI, this may not be possible because Boolean values are (unfortunately) integers: def f(x: int):
assert isinstance(x, int)
print(x, int(x)) # If you remove `int` here, you change things.
f(True)You could detect unnecessary casts, but you have to check that it's not used in any way that would matter, which is a lot trickier. |
|
@NeilGirdhar I made sure to take this into account: All functions listed there either delegate to their corresponding dunder methods or return a strict instance of |
Yes, I wasn't talking about this excellent PR 😄 . I was just responding to the comment that suggested that type inference can be used to discover unnecessary integer casts. |
crates/ruff_linter/src/rules/ruff/rules/unnecessary_cast_to_int.rs
Outdated
Show resolved
Hide resolved
MichaReiser
left a comment
There was a problem hiding this comment.
This looks good to me. I pushed a few smaller nits, updated the documentation, and marked the fix for round(2) as safe. Let me know if that looks good to you and I'll merge
|
@MichaReiser Looks good to me too. Let's get this merged. |
|
I completely missed the party, but I'm amazed by how fast you respond, couldn't appreciate more |
Summary
Resolves #11412.
Test Plan
cargo nextest runandcargo insta test.