Skip to content

Commit d767cb7

Browse files
Handle typo in float call more gracefully
1 parent 4fbd387 commit d767cb7

File tree

3 files changed

+17
-5
lines changed

3 files changed

+17
-5
lines changed

pylint/extensions/code_style.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from __future__ import annotations
66

7+
import difflib
78
from typing import TYPE_CHECKING, TypeGuard, cast
89

910
from astroid import nodes
@@ -127,14 +128,21 @@ def visit_call(self, node: nodes.Call) -> None:
127128
c.isalpha() and c.lower() != "e" for c in node.args[0].value
128129
)
129130
):
130-
is_nan = "nan" in node.args[0].value.lower()
131-
minus = (
132-
"-" if not is_nan and node.args[0].value.startswith("-") else ""
133-
)
131+
value = node.args[0].value.lower()
132+
math_call: str
133+
if "nan" in value:
134+
math_call = "nan"
135+
elif "inf" in value:
136+
math_call = "inf"
137+
else:
138+
math_call = difflib.get_close_matches(
139+
value, ["inf", "nan"], n=1, cutoff=0
140+
)[0]
141+
minus = "-" if math_call == "inf" and value.startswith("-") else ""
134142
self.add_message(
135143
"use-math-not-float",
136144
node=node,
137-
args=(minus, "nan" if is_nan else "inf", node.as_string()),
145+
args=(minus, math_call, node.as_string()),
138146
confidence=INFERENCE,
139147
)
140148

tests/functional/ext/code_style/cs_use_math_not_float.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,5 @@
1414
neg_nan_float = float("-nan") # [use-math-not-float]
1515
pos_nan_float = float("+nan") # [use-math-not-float]
1616
upper_nan_float = float("NaN") # [use-math-not-float]
17+
typo_nan_float = float("nani") # [use-math-not-float]
18+
other_typo_nan_float = float("nna") # [use-math-not-float]

tests/functional/ext/code_style/cs_use_math_not_float.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,5 @@ use-math-not-float:13:12:13:24::math.nan is preferable to float('nan'):INFERENCE
99
use-math-not-float:14:16:14:29::math.nan is preferable to float('-nan'):INFERENCE
1010
use-math-not-float:15:16:15:29::math.nan is preferable to float('+nan'):INFERENCE
1111
use-math-not-float:16:18:16:30::math.nan is preferable to float('NaN'):INFERENCE
12+
use-math-not-float:17:17:17:30::math.nan is preferable to float('nani'):INFERENCE
13+
use-math-not-float:18:23:18:35::math.nan is preferable to float('nna'):INFERENCE

0 commit comments

Comments
 (0)