Skip to content

Commit aa29024

Browse files
committed
Import statements should always be placed after any comments or whitespace.
Addresses issue #18 Imports are already placed after copyright/comments if there's a docstring or shebang in the file. This makes import handling consistent in more cases.
1 parent 2b1755b commit aa29024

File tree

2 files changed

+35
-12
lines changed

2 files changed

+35
-12
lines changed

libmodernize/__init__.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,10 +61,9 @@ def add_future(node, symbol):
6161
import_ = fixer_util.FromImport('__future__',
6262
[Leaf(token.NAME, symbol, prefix=" ")])
6363

64-
# If we're inserting as the first element, ensure any shebang prefix is maintained.
65-
if idx == 0 and node.prefix.startswith('#!'):
66-
import_.prefix = node.prefix
67-
node.prefix = ''
64+
# Place after any comments or whitespace. (copyright, shebang etc.)
65+
import_.prefix = node.prefix
66+
node.prefix = ''
6867

6968
children = [import_, fixer_util.Newline()]
7069
root.insert_child(idx, Node(syms.simple_stmt, children))

tests/test_fix_import.py

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,14 @@
3030
""")
3131

3232
DOCSTRING = ("""\
33-
\"\"\"
33+
\"""
3434
Docstring
35-
\"\"\"
35+
\"""
3636
import foo
3737
""", """\
38-
\"\"\"
38+
\"""
3939
Docstring
40-
\"\"\"
40+
\"""
4141
from __future__ import absolute_import
4242
import foo
4343
""")
@@ -53,15 +53,15 @@
5353

5454
DOCSTING_AND_SHEBANG = ("""\
5555
#!/usr/bin/env python
56-
\"\"\"
56+
\"""
5757
Docstring
58-
\"\"\"
58+
\"""
5959
import foo
6060
""", """\
6161
#!/usr/bin/env python
62-
\"\"\"
62+
\"""
6363
Docstring
64-
\"\"\"
64+
\"""
6565
from __future__ import absolute_import
6666
import foo
6767
""")
@@ -85,6 +85,27 @@
8585
import foo
8686
""")
8787

88+
89+
COPYRIGHT_AND_DOCSTRING = ("""\
90+
#
91+
# Copyright notice
92+
#
93+
94+
\"""Docstring\"""
95+
96+
import foo
97+
""", """\
98+
#
99+
# Copyright notice
100+
#
101+
102+
\"""Docstring\"""
103+
104+
from __future__ import absolute_import
105+
import foo
106+
""")
107+
108+
88109
def test_no_imports():
89110
check_on_input(*NO_IMPORTS)
90111

@@ -108,3 +129,6 @@ def test_import_with_docstring_and_shebang():
108129

109130
def test_import_with_copyright_and_shebang():
110131
check_on_input(*COPYRIGHT_AND_SHEBANG)
132+
133+
def test_import_with_copyright_and_docstring():
134+
check_on_input(*COPYRIGHT_AND_DOCSTRING)

0 commit comments

Comments
 (0)