Skip to content

Commit

Permalink
Add better type deduction for sets, frozensets, and tuples to FURB115
Browse files Browse the repository at this point in the history
  • Loading branch information
dosisod committed Mar 8, 2024
1 parent ae0e502 commit d4e9ee3
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 3 deletions.
25 changes: 22 additions & 3 deletions refurb/checks/readability/no_len_cmp.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,19 @@
NameExpr,
Node,
OpExpr,
TupleExpr,
UnaryExpr,
WhileStmt,
)

from refurb.checks.common import is_mapping, is_sized, stringify
from refurb.checks.common import (
get_mypy_type,
is_mapping,
is_same_type,
is_sized,
mypy_type_to_python_type,
stringify,
)
from refurb.error import Error
from refurb.visitor import METHOD_NODE_MAPPINGS, TraverserVisitor

Expand Down Expand Up @@ -139,8 +147,19 @@ def visit_comparison_expr(self, node: ComparisonExpr) -> None:

case ComparisonExpr(
operators=["==" | "!=" as oper],
operands=[lhs, (ListExpr(items=[]) | DictExpr(items=[]))],
) if is_sized(lhs):
operands=[
lhs,
(
ListExpr(items=[])
| DictExpr(items=[])
| TupleExpr(items=[])
| CallExpr(
callee=NameExpr(fullname="builtins.set" | "builtins.frozenset"),
args=[],
)
) as rhs,
],
) if is_same_type(get_mypy_type(lhs), mypy_type_to_python_type(get_mypy_type(rhs))):
old = stringify(node)
new = stringify(lhs)

Expand Down
9 changes: 9 additions & 0 deletions test/data/err_115.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,11 @@ def mapping_check(m: Mapping[str, str]):
assert len(authors) == 0


assert fruits == frozenset()
assert primes == set()
assert data == ()


# these should not

if len(nums) == 1: ...
Expand Down Expand Up @@ -127,3 +132,7 @@ def __len__(self) -> int:
assert nums <= []

assert len(nums) % 2

assert data == []
assert data == {}
assert data == set()
3 changes: 3 additions & 0 deletions test/data/err_115.txt
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,6 @@ test/data/err_115.py:95:8 [FURB115]: Replace `len(list(authors)) == 0` with `not
test/data/err_115.py:96:8 [FURB115]: Replace `len(authors.keys()) == 0` with `not authors`
test/data/err_115.py:97:8 [FURB115]: Replace `len(authors.values()) == 0` with `not authors`
test/data/err_115.py:98:8 [FURB115]: Replace `len(authors) == 0` with `not authors`
test/data/err_115.py:101:8 [FURB115]: Replace `fruits == frozenset()` with `not fruits`
test/data/err_115.py:102:8 [FURB115]: Replace `primes == set()` with `not primes`
test/data/err_115.py:103:8 [FURB115]: Replace `data == ()` with `not data`

0 comments on commit d4e9ee3

Please sign in to comment.