Skip to content

Commit

Permalink
Fix PyCQA#1964: lines_before_import sometimes ignored
Browse files Browse the repository at this point in the history
The config option `lines_before_import` was ignored if the file only contained
imports + optionally a leading comment.
  • Loading branch information
robsdedude committed Aug 21, 2022
1 parent 12cc5fb commit fa1bdca
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 10 deletions.
2 changes: 1 addition & 1 deletion isort/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ def process(
if not_imports:

if not was_in_quote and config.lines_before_imports > -1:
if line.strip() == "":
if line.strip() == "" and not end_of_file:
lines_before += line
continue
if not import_section:
Expand Down
7 changes: 4 additions & 3 deletions isort/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,10 @@ def sorted_imports(
] == [""]:
formatted_output.pop(imports_tail)

if config.lines_before_imports != -1:
formatted_output[:0] = ["" for line in range(config.lines_before_imports)]
imports_tail += config.lines_before_imports

if len(formatted_output) > imports_tail:
next_construct = ""
tail = formatted_output[imports_tail:]
Expand Down Expand Up @@ -217,9 +221,6 @@ def sorted_imports(
else:
formatted_output[imports_tail:0] = [""]

if config.lines_before_imports != -1:
formatted_output[:0] = ["" for line in range(config.lines_before_imports)]

if parsed.place_imports:
new_out_lines = []
for index, line in enumerate(formatted_output):
Expand Down
13 changes: 7 additions & 6 deletions tests/unit/test_isort.py
Original file line number Diff line number Diff line change
Expand Up @@ -1714,12 +1714,13 @@ def test_order_by_type() -> None:
)


def test_custom_lines_before_import_section() -> None:
"""Test the case where the number of lines to output after imports has been explicitly set."""
test_input = """from a import b
foo = 'bar'
"""
@pytest.mark.parametrize("has_body", [True, False])
# @pytest.mark.parametrize("has_body", [False])
def test_custom_lines_before_import_section(has_body) -> None:
"""Test the case where the number of lines to output before imports has been explicitly set."""
test_input = "from a import b\n"
if has_body:
test_input += "\nfoo = 'bar'\n"

ln = "\n"

Expand Down

0 comments on commit fa1bdca

Please sign in to comment.