Skip to content

Commit 2f67a26

Browse files
committed
[pylint] Detect more exotic NaN literals in PLW0177
1 parent e84406d commit 2f67a26

File tree

3 files changed

+33
-4
lines changed

3 files changed

+33
-4
lines changed

crates/ruff_linter/resources/test/fixtures/pylint/nan_comparison.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,8 @@
9292
# OK
9393
if x == "nan":
9494
pass
95+
96+
# PLW0117
97+
# https://github.com/astral-sh/ruff/issues/18596
98+
assert x == float("-NaN ")
99+
assert x == float(" \n+nan \t")

crates/ruff_linter/src/rules/pylint/rules/nan_comparison.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -117,12 +117,19 @@ fn is_nan_float(expr: &Expr, semantic: &SemanticModel) -> bool {
117117
return false;
118118
};
119119

120-
if !matches!(
121-
value.to_str(),
122-
"nan" | "NaN" | "NAN" | "Nan" | "nAn" | "naN" | "nAN" | "NAn"
123-
) {
120+
if !is_nan_literal(value.to_str()) {
124121
return false;
125122
}
126123

127124
semantic.match_builtin_expr(func, "float")
128125
}
126+
127+
/// Returns `true` if `value` is a string literal that represents NaN.
128+
/// E.g., `"NaN"`, `"-nAn"`, `"+nan"`, or even " -NaN "
129+
fn is_nan_literal(value: &str) -> bool {
130+
let mut value = value.trim();
131+
if matches!(value.trim().chars().next(), Some('+' | '-')) {
132+
value = &value[1..];
133+
}
134+
value.eq_ignore_ascii_case("nan")
135+
}

crates/ruff_linter/src/rules/pylint/snapshots/ruff_linter__rules__pylint__tests__PLW0177_nan_comparison.py.snap

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,3 +107,20 @@ nan_comparison.py:60:10: PLW0177 Comparing against a NaN value; use `math.isnan`
107107
61 |
108108
62 | # No errors
109109
|
110+
111+
nan_comparison.py:98:13: PLW0177 Comparing against a NaN value; use `math.isnan` instead
112+
|
113+
96 | # PLW0117
114+
97 | # https://github.com/astral-sh/ruff/issues/18596
115+
98 | assert x == float("-NaN ")
116+
| ^^^^^^^^^^^^^^ PLW0177
117+
99 | assert x == float(" \n+nan \t")
118+
|
119+
120+
nan_comparison.py:99:13: PLW0177 Comparing against a NaN value; use `math.isnan` instead
121+
|
122+
97 | # https://github.com/astral-sh/ruff/issues/18596
123+
98 | assert x == float("-NaN ")
124+
99 | assert x == float(" \n+nan \t")
125+
| ^^^^^^^^^^^^^^^^^^^^^ PLW0177
126+
|

0 commit comments

Comments
 (0)