[ruff] FURB164 Replace -nan with nan when using the value to construct Decimal (#20391)

## Summary

Fixes #19699

Normalize `Decimal(float("-nan"))` to `Decimal("nan")`.

The same handling is implemented in:

c3e873dd82/crates/ruff_linter/src/rules/refurb/rules/verbose_decimal_constructor.rs (L165)
This commit is contained in:
Takayuki Maeda
2025-09-20 03:04:29 +09:00
committed by GitHub
parent c94ddb590f
commit 8eeca023d6
2 changed files with 17 additions and 5 deletions

View File

@@ -293,7 +293,19 @@ fn handle_non_finite_float_special_case(
return None;
};
let normalized = as_non_finite_float_string_literal(float_arg)?;
let replacement_text = format!(r#"{constructor_name}("{normalized}")"#);
let replacement_text = format!(
r#"{constructor_name}("{}")"#,
// `Decimal.from_float(float(" -nan")) == Decimal("nan")`
if normalized == "-nan" {
// Here we do not attempt to remove just the '-' character.
// It may have been encoded (e.g. as '\N{hyphen-minus}')
// in the original source slice, and the added complexity
// does not make sense for this edge case.
"nan"
} else {
normalized
}
);
Some(Edit::range_replacement(replacement_text, call.range()))
}

View File

@@ -363,7 +363,7 @@ help: Replace with `Decimal` constructor
21 | _ = Decimal.from_float(float("-Infinity"))
22 | _ = Decimal.from_float(float("nan"))
- _ = Decimal.from_float(float("-NaN"))
23 + _ = Decimal("-nan")
23 + _ = Decimal("nan")
24 | _ = Decimal.from_float(float(" \n+nan \t"))
25 | _ = Decimal.from_float(float(" iNf\n\t "))
26 | _ = Decimal.from_float(float(" -inF\n \t"))
@@ -655,7 +655,7 @@ help: Replace with `Decimal` constructor
62 |
63 | # Cases with non-finite floats - should produce safe fixes
- _ = Decimal.from_float(float("-nan"))
64 + _ = Decimal("-nan")
64 + _ = Decimal("nan")
65 | _ = Decimal.from_float(float("\x2dnan"))
66 | _ = Decimal.from_float(float("\N{HYPHEN-MINUS}nan"))
@@ -673,7 +673,7 @@ help: Replace with `Decimal` constructor
63 | # Cases with non-finite floats - should produce safe fixes
64 | _ = Decimal.from_float(float("-nan"))
- _ = Decimal.from_float(float("\x2dnan"))
65 + _ = Decimal("-nan")
65 + _ = Decimal("nan")
66 | _ = Decimal.from_float(float("\N{HYPHEN-MINUS}nan"))
FURB164 [*] Verbose method `from_float` in `Decimal` construction
@@ -689,4 +689,4 @@ help: Replace with `Decimal` constructor
64 | _ = Decimal.from_float(float("-nan"))
65 | _ = Decimal.from_float(float("\x2dnan"))
- _ = Decimal.from_float(float("\N{HYPHEN-MINUS}nan"))
66 + _ = Decimal("-nan")
66 + _ = Decimal("nan")