Skip to content

Commit

Permalink
Fix C402/C404 false positive for dict() with kwargs (#458)
Browse files Browse the repository at this point in the history
  • Loading branch information
adamchainz committed Oct 29, 2022
1 parent 7d8f47f commit e655c26
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 1 deletion.
4 changes: 4 additions & 0 deletions HISTORY.rst
Expand Up @@ -2,6 +2,10 @@
History
=======

* Fix false positive in rules C402 and C404 for ``dict()`` calls with keyword arguments.

Thanks to Anders Kaseorg for the report in `Issue #457 <https://github.com/adamchainz/flake8-comprehensions/issues/457>`__.

3.10.0 (2022-05-19)
-------------------

Expand Down
3 changes: 2 additions & 1 deletion src/flake8_comprehensions/__init__.py
Expand Up @@ -68,10 +68,11 @@ def run(self) -> Generator[tuple[int, int, str, type[Any]], None, None]:

elif (
num_positional_args == 1
and node.func.id == "dict"
and len(node.keywords) == 0
and isinstance(node.args[0], (ast.GeneratorExp, ast.ListComp))
and isinstance(node.args[0].elt, ast.Tuple)
and len(node.args[0].elt.elts) == 2
and node.func.id == "dict"
):
if isinstance(node.args[0], ast.GeneratorExp):
msg = "C402"
Expand Down
4 changes: 4 additions & 0 deletions tests/test_flake8_comprehensions.py
Expand Up @@ -129,6 +129,8 @@ def test_C401_fail(code, failures, flake8_path):
foo = [('a', 1), ('b', 2), ('c', 3)]
dict(pair for pair in foo if pair[1] % 2 == 0)
""",
# Previously a false positive:
"dict(((x, str(x)) for x in range(10)), c=1)",
],
)
def test_C402_pass(code, flake8_path):
Expand Down Expand Up @@ -204,6 +206,8 @@ def test_C403_fail(code, failures, flake8_path):
"foo = {x: x for x in range(10)}",
# Previously a false positive:
"foo = dict([x.split('=') for x in ['a=1', 'b=2']])",
# Previously a false positive:
"dict([(x, x) for x in range(10)], y=2)",
],
)
def test_C404_pass(code, flake8_path):
Expand Down

0 comments on commit e655c26

Please sign in to comment.