From 4343c41ca3d52e75af5e95f6b86a6053bcbd9a57 Mon Sep 17 00:00:00 2001 From: Hideo Hattori Date: Tue, 30 Oct 2018 12:49:56 +0900 Subject: [PATCH] fix e402 fixed method when import some modules (for #447) --- autopep8.py | 12 ++++++++++-- test/test_autopep8.py | 23 +++++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/autopep8.py b/autopep8.py index 1372d268..53a84467 100755 --- a/autopep8.py +++ b/autopep8.py @@ -873,11 +873,19 @@ def fix_e401(self, result): def fix_e402(self, result): (line_index, offset, target) = get_index_offset_contents(result, self.source) + for i in range(1, 100): + line = "".join(self.source[line_index:line_index+i]) + try: + generate_tokens("".join(line)) + except (SyntaxError, tokenize.TokenError): + continue + break if not (target in self.imports and self.imports[target] != line_index): mod_offset = get_module_imports_on_top_of_file(self.source, line_index) - self.source[mod_offset] = target + self.source[mod_offset] - self.source[line_index] = '' + self.source[mod_offset] = line + self.source[mod_offset] + for offset in range(i): + self.source[line_index+offset] = '' def fix_long_line_logically(self, result, logical): """Try to make lines fit within --max-line-length characters.""" diff --git a/test/test_autopep8.py b/test/test_autopep8.py index 26846598..03e3084e 100755 --- a/test/test_autopep8.py +++ b/test/test_autopep8.py @@ -2416,6 +2416,29 @@ def test_e402_duplicate_module(self): with autopep8_context(line) as result: self.assertEqual(fixed, result) + def test_e402_import_some_modules(self): + line = """\ +a = 1 +from csv import ( + reader, + writer, +) +import os +print(os, reader, writer) +import os +""" + fixed = """\ +import os +from csv import ( + reader, + writer, +) +a = 1 +print(os, reader, writer) +""" + with autopep8_context(line) as result: + self.assertEqual(fixed, result) + def test_e501_basic(self): line = """\