diff --git a/refurb/checks/common.py b/refurb/checks/common.py index 5bcc097..8895cd5 100644 --- a/refurb/checks/common.py +++ b/refurb/checks/common.py @@ -329,6 +329,10 @@ def _stringify(node: Node) -> str: case TupleExpr(items=items): inner = ", ".join(stringify(x) for x in items) + if len(items) == 1: + # single element tuples need a trailing comma + inner += "," + return f"({inner})" case CallExpr(): @@ -387,6 +391,11 @@ def _stringify(node: Node) -> str: return f"[{inner}]" + case SetExpr(items=items): + inner = ", ".join(stringify(x) for x in items) + + return f"{{{inner}}}" + raise ValueError diff --git a/refurb/checks/iterable/no_single_item_in.py b/refurb/checks/iterable/no_single_item_in.py index 591fd45..87470ca 100644 --- a/refurb/checks/iterable/no_single_item_in.py +++ b/refurb/checks/iterable/no_single_item_in.py @@ -1,7 +1,8 @@ from dataclasses import dataclass -from mypy.nodes import ComparisonExpr, ListExpr, TupleExpr +from mypy.nodes import ComparisonExpr, ListExpr, SetExpr, TupleExpr +from refurb.checks.common import stringify from refurb.error import Error @@ -34,13 +35,12 @@ def check(node: ComparisonExpr, errors: list[Error]) -> None: match node: case ComparisonExpr( operators=["in" | "not in" as oper], - operands=[_, ListExpr() | TupleExpr() as expr], + operands=[lhs, ListExpr() | TupleExpr() | SetExpr() as expr], ) if len(expr.items) == 1: new_oper = "==" if oper == "in" else "!=" - if isinstance(expr, ListExpr): - msg = f"Replace `x {oper} [y]` with `x {new_oper} y`" - else: - msg = f"Replace `x {oper} (y,)` with `x {new_oper} y`" + new = f"{stringify(lhs)} {new_oper} {stringify(expr.items[0])}" + + msg = f"Replace `{stringify(node)}` with `{new}`" errors.append(ErrorInfo.from_node(node, msg)) diff --git a/test/data/err_171.py b/test/data/err_171.py index fdc2b30..6cbc524 100644 --- a/test/data/err_171.py +++ b/test/data/err_171.py @@ -2,8 +2,10 @@ _ = 1 in (1,) _ = 1 in [1] # noqa: FURB109 +_ = 1 in {1} _ = 1 not in (1,) _ = 1 not in [1] # noqa: FURB109 +_ = 1 not in {1} # noqa: FURB109 # these should not diff --git a/test/data/err_171.txt b/test/data/err_171.txt index c952f32..b0cfad7 100644 --- a/test/data/err_171.txt +++ b/test/data/err_171.txt @@ -1,4 +1,6 @@ -test/data/err_171.py:3:5 [FURB171]: Replace `x in (y,)` with `x == y` -test/data/err_171.py:4:5 [FURB171]: Replace `x in [y]` with `x == y` -test/data/err_171.py:5:5 [FURB171]: Replace `x not in (y,)` with `x != y` -test/data/err_171.py:6:5 [FURB171]: Replace `x not in [y]` with `x != y` +test/data/err_171.py:3:5 [FURB171]: Replace `1 in (1,)` with `1 == 1` +test/data/err_171.py:4:5 [FURB171]: Replace `1 in [1]` with `1 == 1` +test/data/err_171.py:5:5 [FURB171]: Replace `1 in {1}` with `1 == 1` +test/data/err_171.py:6:5 [FURB171]: Replace `1 not in (1,)` with `1 != 1` +test/data/err_171.py:7:5 [FURB171]: Replace `1 not in [1]` with `1 != 1` +test/data/err_171.py:8:5 [FURB171]: Replace `1 not in {1}` with `1 != 1`