diff --git a/isort/output.py b/isort/output.py index 1be048b12..ea22115b5 100644 --- a/isort/output.py +++ b/isort/output.py @@ -173,11 +173,17 @@ def sorted_imports( next_construct = line break + # A form feed may have been hoisted in front of this line from the blank + # lines above it (see ``overflow_form_feeds`` below). Form feeds are + # whitespace that resets the indentation column, so they do not stop the + # line from being a statement declaration. if config.lines_after_imports != -1: lines_after_imports = config.lines_after_imports if config.profile == "black" and extension == "pyi": # special case for black lines_after_imports = 1 - elif extension != "pyi" and next_construct.startswith(STATEMENT_DECLARATIONS): + elif extension != "pyi" and next_construct.lstrip("\f").startswith( + STATEMENT_DECLARATIONS + ): lines_after_imports = 2 else: lines_after_imports = 1 diff --git a/tests/unit/test_regressions.py b/tests/unit/test_regressions.py index 1d21c9c41..5f070f365 100644 --- a/tests/unit/test_regressions.py +++ b/tests/unit/test_regressions.py @@ -252,6 +252,22 @@ def test_form_feed_blank_line_not_removed_issue_2562() -> None: assert isort.code(test_input, lines_after_imports=2) == test_input +@pytest.mark.parametrize( + "declaration", ["def f():\n pass", "class C:\n pass", "async def f():\n pass"] +) +def test_form_feed_hidden_declaration_keeps_two_blank_lines_issue_2562(declaration: str) -> None: + """A form feed hoisted in front of a top level declaration must not hide it. + + ``\\f`` is whitespace and resets the indentation column, so ``\\fdef f():`` is still a + statement declaration: it keeps ``lines_after_imports`` at 2 and the output stays + stable. See: https://github.com/pycqa/isort/issues/2562 + """ + test_input = f"import sys\n\n\n\f\n{declaration}\n" + expected = f"import sys\n\n\n\f{declaration}\n" + assert isort.code(test_input) == expected + assert isort.code(expected) == expected + + def test_force_single_line_shouldnt_remove_preceding_comment_lines_issue_1296() -> None: """Tests to ensure force_single_line setting doesn't result in lost comments. See: https://github.com/pycqa/isort/issues/1296