Skip to content

Commit

Permalink
Improve FURB111, bump version:
Browse files Browse the repository at this point in the history
Add support for detecting lambdas returning `[]`, `{}`, and `()` which can be
replaced with the `list`, `dict`, and `tuple` functions instead.

Also bump package version for update.
  • Loading branch information
dosisod committed Sep 8, 2023
1 parent 918ffe5 commit 10084cf
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "refurb"
version = "1.20.0"
version = "1.21.0"
description = "A tool for refurbish and modernize Python codebases"
authors = ["dosisod"]
license = "GPL-3.0-only"
Expand Down
32 changes: 32 additions & 0 deletions refurb/checks/readability/use_func_name.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@
Argument,
Block,
CallExpr,
DictExpr,
Expression,
LambdaExpr,
ListExpr,
NameExpr,
ReturnStmt,
TupleExpr,
)

from refurb.error import Error
Expand Down Expand Up @@ -76,3 +79,32 @@ def check(node: LambdaExpr, errors: list[Error]) -> None:
f"Replace `{_lambda}: {func_name}({arg_names})` with `{func_name}`", # noqa: E501
)
)

case LambdaExpr(
arguments=[],
body=Block(
body=[
ReturnStmt(
expr=ListExpr(items=[])
| DictExpr(items=[])
| TupleExpr(items=[]) as expr,
)
],
),
):
if isinstance(expr, ListExpr):
old = "[]"
new = "list"
elif isinstance(expr, DictExpr):
old = "{}"
new = "dict"
else:
old = "()"
new = "tuple"

errors.append(
ErrorInfo.from_node(
node,
f"Replace `lambda: {old}` with `{new}`",
)
)
8 changes: 8 additions & 0 deletions test/data/err_111.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ def f(x, y):
lambda x: bool(x)
lambda x, y: f(x, y)

lambda: []
lambda: {}
lambda: ()


# these will not

Expand All @@ -19,3 +23,7 @@ def f(x, y):
lambda x: print(*x)
lambda x: print(**x)
lambda: True

lambda: [1, 2, 3]
lambda: {"k": "v"}
lambda: (1, 2, 3)
3 changes: 3 additions & 0 deletions test/data/err_111.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
test/data/err_111.py:7:1 [FURB111]: Replace `lambda: print()` with `print`
test/data/err_111.py:8:1 [FURB111]: Replace `lambda x: bool(x)` with `bool`
test/data/err_111.py:9:1 [FURB111]: Replace `lambda x, y: f(x, y)` with `f`
test/data/err_111.py:11:1 [FURB111]: Replace `lambda: []` with `list`
test/data/err_111.py:12:1 [FURB111]: Replace `lambda: {}` with `dict`
test/data/err_111.py:13:1 [FURB111]: Replace `lambda: ()` with `tuple`

0 comments on commit 10084cf

Please sign in to comment.