Skip to content

Commit

Permalink
Improve FURB164 error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
dosisod committed Dec 27, 2023
1 parent 1e49b1d commit 6103901
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 17 deletions.
26 changes: 14 additions & 12 deletions refurb/checks/readability/no_from_float.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from mypy.nodes import CallExpr, MemberExpr, RefExpr

from refurb.checks.common import stringify
from refurb.error import Error


Expand Down Expand Up @@ -33,27 +34,28 @@ class ErrorInfo(Error):


KNOWN_FUNCS = {
"Decimal.from_float",
"Fraction.from_float",
"Fraction.from_decimal",
"_decimal.Decimal.from_float",
"fractions.Fraction.from_float",
"fractions.Fraction.from_decimal",
}


def check(node: CallExpr, errors: list[Error]) -> None:
match node:
case CallExpr(
callee=MemberExpr(
expr=RefExpr(
fullname="_decimal.Decimal" | "fractions.Fraction",
name=klass, # type: ignore
),
expr=RefExpr(fullname="_decimal.Decimal" | "fractions.Fraction") as ref,
name="from_float" | "from_decimal" as ctor,
),
args=[_],
args=[arg],
):
func = f"{klass}.{ctor}"

if func not in KNOWN_FUNCS:
if f"{ref.fullname}.{ctor}" not in KNOWN_FUNCS:
return

errors.append(ErrorInfo.from_node(node, f"Replace `{func}(x)` with `{klass}(x)`"))
base = stringify(ref)
arg = stringify(arg) # type: ignore

old = f"{base}.{ctor}({arg})"
new = f"{base}({arg})"

errors.append(ErrorInfo.from_node(node, f"Replace `{old}` with `{new}`"))
10 changes: 5 additions & 5 deletions test/data/err_164.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
test/data/err_164.py:8:5 [FURB164]: Replace `Decimal.from_float(x)` with `Decimal(x)`
test/data/err_164.py:9:5 [FURB164]: Replace `Fraction.from_float(x)` with `Fraction(x)`
test/data/err_164.py:10:5 [FURB164]: Replace `Fraction.from_decimal(x)` with `Fraction(x)`
test/data/err_164.py:11:5 [FURB164]: Replace `Decimal.from_float(x)` with `Decimal(x)`
test/data/err_164.py:12:5 [FURB164]: Replace `Fraction.from_float(x)` with `Fraction(x)`
test/data/err_164.py:8:5 [FURB164]: Replace `Decimal.from_float(123)` with `Decimal(123)`
test/data/err_164.py:9:5 [FURB164]: Replace `Fraction.from_float(123)` with `Fraction(123)`
test/data/err_164.py:10:5 [FURB164]: Replace `Fraction.from_decimal(Decimal(123))` with `Fraction(Decimal(123))`
test/data/err_164.py:11:5 [FURB164]: Replace `decimal.Decimal.from_float(123)` with `decimal.Decimal(123)`
test/data/err_164.py:12:5 [FURB164]: Replace `fractions.Fraction.from_float(123)` with `fractions.Fraction(123)`

0 comments on commit 6103901

Please sign in to comment.