From 10084cfbc25009da26cf278f403ce9ac66c300f0 Mon Sep 17 00:00:00 2001 From: dosisod <39638017+dosisod@users.noreply.github.com> Date: Fri, 8 Sep 2023 14:59:28 -0700 Subject: [PATCH] Improve FURB111, bump version: 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. --- pyproject.toml | 2 +- refurb/checks/readability/use_func_name.py | 32 ++++++++++++++++++++++ test/data/err_111.py | 8 ++++++ test/data/err_111.txt | 3 ++ 4 files changed, 44 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index db1ce6c..6c29a21 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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" diff --git a/refurb/checks/readability/use_func_name.py b/refurb/checks/readability/use_func_name.py index 14b4a04..6d87ad4 100644 --- a/refurb/checks/readability/use_func_name.py +++ b/refurb/checks/readability/use_func_name.py @@ -5,10 +5,13 @@ Argument, Block, CallExpr, + DictExpr, Expression, LambdaExpr, + ListExpr, NameExpr, ReturnStmt, + TupleExpr, ) from refurb.error import Error @@ -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}`", + ) + ) diff --git a/test/data/err_111.py b/test/data/err_111.py index c35f52f..d926415 100644 --- a/test/data/err_111.py +++ b/test/data/err_111.py @@ -8,6 +8,10 @@ def f(x, y): lambda x: bool(x) lambda x, y: f(x, y) +lambda: [] +lambda: {} +lambda: () + # these will not @@ -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) diff --git a/test/data/err_111.txt b/test/data/err_111.txt index c2d164c..93b53f9 100644 --- a/test/data/err_111.txt +++ b/test/data/err_111.txt @@ -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`