Skip to content

Commit

Permalink
Expand C416 to dict comprehensions
Browse files Browse the repository at this point in the history
  • Loading branch information
Skylion007 committed Mar 17, 2023
1 parent c95c753 commit 7f1044f
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 6 deletions.
5 changes: 3 additions & 2 deletions README.rst
Expand Up @@ -150,13 +150,14 @@ For example:
* Rewrite ``sorted(iterable)[::-1]`` as ``sorted(iterable, reverse=True)``
* Rewrite ``reversed(iterable[::-1])`` as ``iterable``

C416: Unnecessary ``<list/set>`` comprehension - rewrite using ``<list/set>``\().
C416: Unnecessary ``<dict/list/set>`` comprehension - rewrite using ``<dict/list/set>``\().
---------------------------------------------------------------------------------

It's unnecessary to use a list comprehension if the elements are unchanged.
The iterable should be wrapped in ``list()`` or ``set()`` instead.
The iterable should be wrapped in ``dict()``, ``list()``, or ``set()`` instead.
For example:

* Rewrite ``{a:b for a, b in iterable}`` as ``dict(iterable)``
* Rewrite ``[x for x in iterable]`` as ``list(iterable)``
* Rewrite ``{x for x in iterable}`` as ``set(iterable)``

Expand Down
23 changes: 19 additions & 4 deletions src/flake8_comprehensions/__init__.py
Expand Up @@ -295,15 +295,30 @@ def run(self) -> Generator[tuple[int, int, str, type[Any]], None, None]:
type(self),
)

elif isinstance(node, (ast.ListComp, ast.SetComp)):
elif isinstance(node, (ast.DictComp, ast.ListComp, ast.SetComp)):
if (
len(node.generators) == 1
and not node.generators[0].ifs
and not node.generators[0].is_async
and (
isinstance(node.elt, ast.Name)
and isinstance(node.generators[0].target, ast.Name)
and node.elt.id == node.generators[0].target.id
(
isinstance(node, (ast.ListComp, ast.SetComp))
and isinstance(node.elt, ast.Name)
and isinstance(node.generators[0].target, ast.Name)
and node.elt.id == node.generators[0].target.id
)
or (
isinstance(node, ast.DictComp)
and isinstance(node.key, ast.Name)
and isinstance(node.value, ast.Name)
and isinstance(node.generators[0].target, ast.Tuple)
and tuple(
x.id
for x in node.generators[0].target.elts
if isinstance(x, ast.Name)
)
== (node.key.id, node.value.id)
)
)
):
yield (
Expand Down
14 changes: 14 additions & 0 deletions tests/test_flake8_comprehensions.py
Expand Up @@ -810,6 +810,20 @@ def test_C416_pass(code, flake8_path):
+ "rewrite using set().",
],
),
(
"{x: y for x, y in zip(range(5), range(5))}",
[
"./example.py:1:1: C416 Unnecessary dict comprehension - "
+ "rewrite using dict().",
],
),
(
"{x: y for (x, y) in zip(range(5), range(5))}",
[
"./example.py:1:1: C416 Unnecessary dict comprehension - "
+ "rewrite using dict().",
],
),
],
)
def test_C416_fail(code, failures, flake8_path):
Expand Down

0 comments on commit 7f1044f

Please sign in to comment.