Skip to content

Commit

Permalink
Narrow how much we filter out complex cases
Browse files Browse the repository at this point in the history
  • Loading branch information
myint committed Jan 4, 2018
1 parent c161460 commit d940d44
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 16 deletions.
45 changes: 29 additions & 16 deletions autoflake.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,25 +151,38 @@ def duplicate_key_line_numbers(messages, source):
if isinstance(message, pyflakes.messages.MultiValueRepeatedKeyLiteral)]

if messages:
good = True
# Filter out complex cases. We don't want to bother trying to parse
# this stuff and get it right.
# this stuff and get it right. We can do it on a key-by-key basis.

key_to_messages = create_key_to_messages_dict(messages)

lines = source.split('\n')
for message in messages:
line = lines[message.lineno - 1]
key = message.message_args[0]

if (
line.rstrip().endswith((':', '\\')) or
not dict_entry_has_key(line, key) or
'#' in line or
not line.rstrip().endswith(',')
):
good = False

if good:

for (key, messages) in key_to_messages.items():
good = True
for message in messages:
yield message.lineno
line = lines[message.lineno - 1]
key = message.message_args[0]

if (
line.rstrip().endswith((':', '\\')) or
not dict_entry_has_key(line, key) or
'#' in line or
not line.rstrip().endswith(',')
):
good = False

if good:
for message in messages:
yield message.lineno


def create_key_to_messages_dict(messages):
"""Return dict mapping the key to list of messages."""
dictionary = collections.defaultdict(lambda: [])
for message in messages:
dictionary[message.message_args[0]].append(message)
return dictionary


def check(source):
Expand Down
24 changes: 24 additions & 0 deletions test_autoflake.py
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,30 @@ def test_filter_code_should_ignore_complex_case_of_duplicate_key(self):
''.join(autoflake.filter_code(code,
remove_duplicate_keys=True)))

def test_filter_code_should_ignore_complex_case_of_duplicate_key_partially(
self):
"""We only handle simple cases."""
code = """\
a = {(0,1): 1, (0, 1): 'two',
(0,1): 3,
(2,3): 4,
(2,3): 4,
(2,3): 5,
}
print(a)
"""

self.assertEqual(
"""\
a = {(0,1): 1, (0, 1): 'two',
(0,1): 3,
(2,3): 5,
}
print(a)
""",
''.join(autoflake.filter_code(code,
remove_duplicate_keys=True)))

def test_filter_code_should_ignore_more_cases_of_duplicate_key(self):
"""We only handle simple cases."""
code = """\
Expand Down

0 comments on commit d940d44

Please sign in to comment.