From 999961af756848213a2953e299572ff84f60750d Mon Sep 17 00:00:00 2001 From: Timothy Crosley Date: Wed, 7 Jul 2021 23:53:38 -0700 Subject: [PATCH 1/2] Fix issue #1769: Add imports can be added to incorrect location --- isort/core.py | 10 ++++++---- tests/unit/test_regressions.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 4 deletions(-) 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="""""" +''' + ) From b44400369a7566a45df03224cbf0466ec5f9cd4e Mon Sep 17 00:00:00 2001 From: Timothy Crosley Date: Wed, 7 Jul 2021 23:58:25 -0700 Subject: [PATCH 2/2] Add change to changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4863d54ce..bf91b4d73 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 - Improved behavior of `isort --check --atomic` against Cython files. + - Fixed #1769: Future imports added below assignments when no other imports present. ### 5.9.1 June 21st 2021 [hotfix] - Fixed #1758: projects with many files and skip_ignore set can lead to a command-line overload.