Skip to content

Commit

Permalink
Fix issue #1769: Add imports can be added to incorrect location
Browse files Browse the repository at this point in the history
  • Loading branch information
timothycrosley committed Jul 8, 2021
1 parent 191e165 commit 999961a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
10 changes: 6 additions & 4 deletions isort/core.py
Expand Up @@ -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
Expand Down Expand Up @@ -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 = []

Expand Down
30 changes: 30 additions & 0 deletions tests/unit/test_regressions.py
Expand Up @@ -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=""""""
'''
)

0 comments on commit 999961a

Please sign in to comment.