diff --git a/README.rst b/README.rst index b4391d4..2e73c3b 100644 --- a/README.rst +++ b/README.rst @@ -150,13 +150,14 @@ For example: * Rewrite ``sorted(iterable)[::-1]`` as ``sorted(iterable, reverse=True)`` * Rewrite ``reversed(iterable[::-1])`` as ``iterable`` -C416: Unnecessary ```` comprehension - rewrite using ````\(). +C416: Unnecessary ```` comprehension - rewrite using ````\(). --------------------------------------------------------------------------------- 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)`` diff --git a/src/flake8_comprehensions/__init__.py b/src/flake8_comprehensions/__init__.py index 11e5563..d6203e6 100644 --- a/src/flake8_comprehensions/__init__.py +++ b/src/flake8_comprehensions/__init__.py @@ -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 ( diff --git a/tests/test_flake8_comprehensions.py b/tests/test_flake8_comprehensions.py index 5e9626a..bf0a0e8 100644 --- a/tests/test_flake8_comprehensions.py +++ b/tests/test_flake8_comprehensions.py @@ -810,6 +810,13 @@ 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().", + ], + ), ], ) def test_C416_fail(code, failures, flake8_path):