Skip to content

Commit 2b1755b

Browse files
committed
Import statements should be placed after the shebang.
Addresses issue #18 Imports are also placed after any comments (such as copyright notices), to be consistent with the existing import placement in files with module docstrings.
1 parent 8b21240 commit 2b1755b

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

libmodernize/__init__.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,12 @@ def add_future(node, symbol):
6060

6161
import_ = fixer_util.FromImport('__future__',
6262
[Leaf(token.NAME, symbol, prefix=" ")])
63+
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 = ''
68+
6369
children = [import_, fixer_util.Newline()]
6470
root.insert_child(idx, Node(syms.simple_stmt, children))
6571

tests/test_fix_import.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,61 @@
2929
import foo
3030
""")
3131

32+
DOCSTRING = ("""\
33+
\"\"\"
34+
Docstring
35+
\"\"\"
36+
import foo
37+
""", """\
38+
\"\"\"
39+
Docstring
40+
\"\"\"
41+
from __future__ import absolute_import
42+
import foo
43+
""")
44+
45+
SHEBANG = ("""\
46+
#!/usr/bin/env python
47+
import foo
48+
""", """\
49+
#!/usr/bin/env python
50+
from __future__ import absolute_import
51+
import foo
52+
""")
53+
54+
DOCSTING_AND_SHEBANG = ("""\
55+
#!/usr/bin/env python
56+
\"\"\"
57+
Docstring
58+
\"\"\"
59+
import foo
60+
""", """\
61+
#!/usr/bin/env python
62+
\"\"\"
63+
Docstring
64+
\"\"\"
65+
from __future__ import absolute_import
66+
import foo
67+
""")
68+
69+
COPYRIGHT_AND_SHEBANG = ("""\
70+
#!/usr/bin/env python
71+
72+
#
73+
# Copyright notice
74+
#
75+
76+
import foo
77+
""", """\
78+
#!/usr/bin/env python
79+
80+
#
81+
# Copyright notice
82+
#
83+
84+
from __future__ import absolute_import
85+
import foo
86+
""")
3287

3388
def test_no_imports():
3489
check_on_input(*NO_IMPORTS)
@@ -41,3 +96,15 @@ def test_only_normal_imports():
4196

4297
def test_normal_and_future_imports():
4398
check_on_input(*NORMAL_AND_FUTURE_IMPORTS)
99+
100+
def test_import_with_docstring():
101+
check_on_input(*DOCSTRING)
102+
103+
def test_import_with_shebang():
104+
check_on_input(*SHEBANG)
105+
106+
def test_import_with_docstring_and_shebang():
107+
check_on_input(*DOCSTING_AND_SHEBANG)
108+
109+
def test_import_with_copyright_and_shebang():
110+
check_on_input(*COPYRIGHT_AND_SHEBANG)

0 commit comments

Comments
 (0)