diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ba31082c..dc51d2278 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ Find out more about isort's release policy [here](https://pycqa.github.io/isort/ ### 5.9.2 TBD - Improved behavior of `isort --check --atomic` against Cython files. + - Fixed #1769: Future imports added below assignments when no other imports present. - Fixed #1772: skip-gitignore will check files not in the git repository. - Fixed #1762: in some cases when skip-gitignore is set, isort fails to skip any files. diff --git a/isort/core.py b/isort/core.py index 7b2910da5..4b24e45cd 100644 --- a/isort/core.py +++ b/isort/core.py @@ -55,6 +55,7 @@ def process( next_import_section: str = "" next_cimports: bool = False in_quote: str = "" + was_in_quote: bool = False first_comment_index_start: int = -1 first_comment_index_end: int = -1 contains_imports: bool = False @@ -332,14 +333,15 @@ def process( and (stripped_line or end_of_file) and not config.append_only and not in_top_comment - and not in_quote + and not was_in_quote and not import_section and not line.lstrip().startswith(COMMENT_INDICATORS) - and not line.rstrip().endswith(DOCSTRING_INDICATORS) + and not (line.rstrip().endswith(DOCSTRING_INDICATORS) and "=" not in line) ): - import_section = line_separator.join(add_imports) + line_separator + add_line_separator = line_separator or "\n" + import_section = add_line_separator.join(add_imports) + add_line_separator if end_of_file and index != 0: - output_stream.write(line_separator) + output_stream.write(add_line_separator) contains_imports = True add_imports = [] diff --git a/tests/unit/test_regressions.py b/tests/unit/test_regressions.py index 388aa8d38..449f83d53 100644 --- a/tests/unit/test_regressions.py +++ b/tests/unit/test_regressions.py @@ -1798,3 +1798,33 @@ def test_isort_should_keep_multiple_noqa_comments_force_single_line_mode_issue_1 profile="black", force_single_line=True, ) + + +def test_isort_should_only_add_imports_to_valid_location_issue_1769(): + assert ( + isort.code( + '''v = """ +""".split( + "\n" +) +''', + add_imports=["from __future__ import annotations"], + ) + == '''from __future__ import annotations + +v = """ +""".split( + "\n" +) +''' + ) + assert ( + isort.code( + '''v=""""""''', + add_imports=["from __future__ import annotations"], + ) + == '''from __future__ import annotations + +v="""""" +''' + )