Skip to content

Commit

Permalink
Fix false positive in C404 (#195)
Browse files Browse the repository at this point in the history
Fixes #194.
  • Loading branch information
adamchainz committed Nov 13, 2019
1 parent effbbb2 commit a144cc9
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 16 deletions.
2 changes: 2 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ Pending Release
---------------

* Update Python support to 3.5-3.8.
* Fix false positives for C404 for list comprehensions not directly creating
tuples.

3.0.1 (2019-10-28)
------------------
Expand Down
14 changes: 8 additions & 6 deletions src/flake8_comprehensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,26 +56,28 @@ def run(self):

elif (
num_positional_args == 1
and isinstance(node.args[0], ast.GeneratorExp)
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"
else:
msg = "C404"
yield (
node.lineno,
node.col_offset,
self.messages["C402"],
self.messages[msg],
type(self),
)

elif (
num_positional_args == 1
and isinstance(node.args[0], ast.ListComp)
and node.func.id in ("list", "set", "dict")
and node.func.id in ("list", "set")
):
msg_key = {"list": "C411", "set": "C403", "dict": "C404"}[
node.func.id
]
msg_key = {"list": "C411", "set": "C403"}[node.func.id]
yield (
node.lineno,
node.col_offset,
Expand Down
19 changes: 9 additions & 10 deletions tests/test_flake8_comprehensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,21 +192,20 @@ def test_C403_fail_1(flake8dir):


def test_C404_pass_1(flake8dir):
flake8dir.make_example_py(
"""
foo = {x: x for x in range(10)}
"""
)
flake8dir.make_example_py("foo = {x: x for x in range(10)}")
result = flake8dir.run_flake8()
assert result.out_lines == []


def test_C404_pass_2(flake8dir):
# Previously a false positive
flake8dir.make_example_py("foo = dict([x.split('=') for x in ['a=1', 'b=2']])")
result = flake8dir.run_flake8()
assert result.out_lines == []


def test_C404_fail_1(flake8dir):
flake8dir.make_example_py(
"""
foo = dict([(x, x) for x in range(10)])
"""
)
flake8dir.make_example_py("foo = dict([(x, x) for x in range(10)])")
result = flake8dir.run_flake8()
assert result.out_lines == [
"./example.py:1:7: C404 Unnecessary list comprehension - rewrite as a "
Expand Down

0 comments on commit a144cc9

Please sign in to comment.