Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue/1769 #1775

Merged
merged 3 commits into from Jul 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -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.

Expand Down
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=""""""
'''
)