Skip to content

Commit

Permalink
Merge pull request #461 from Hanaasagi/fix-import-moved-above-future-…
Browse files Browse the repository at this point in the history
…import

fix import moved above a future import
  • Loading branch information
hhatto authored Jan 12, 2019
2 parents 6552e7c + 9cd6ad5 commit 89886b4
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
11 changes: 10 additions & 1 deletion autopep8.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ class documentation for more information.
import textwrap
import token
import tokenize
import ast

import pycodestyle

Expand Down Expand Up @@ -1402,14 +1403,22 @@ def is_string_literal(line):
if line and line[0] in 'rR':
line = line[1:]
return line and (line[0] == '"' or line[0] == "'")

def is_future_import(line):
nodes = ast.parse(line)
for n in nodes.body:
if isinstance(n, ast.ImportFrom) and n.module == '__future__':
return True
return False

allowed_try_keywords = ('try', 'except', 'else', 'finally')
for cnt, line in enumerate(source):
if not line.rstrip():
continue
elif line.startswith('#'):
continue
if line.startswith('import ') or line.startswith('from '):
if cnt == import_line_index:
if cnt == import_line_index or is_future_import(line):
continue
return cnt
elif pycodestyle.DUNDER_REGEX.match(line):
Expand Down
6 changes: 6 additions & 0 deletions test/test_autopep8.py
Original file line number Diff line number Diff line change
Expand Up @@ -2416,6 +2416,12 @@ def test_e402_duplicate_module(self):
with autopep8_context(line) as result:
self.assertEqual(fixed, result)

def test_e402_with_future_import(self):
line = 'from __future__ import print_function\na = 1\nimport os\n'
fixed = 'from __future__ import print_function\nimport os\na = 1\n'
with autopep8_context(line) as result:
self.assertEqual(fixed, result)

def test_e402_import_some_modules(self):
line = """\
a = 1
Expand Down

0 comments on commit 89886b4

Please sign in to comment.