Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix false positive in C404 #195

Merged
merged 1 commit into from
Nov 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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