Skip to content

Commit

Permalink
Merge pull request #1430 from PyCQA/issue/1427/isort-shouldnt-move-im…
Browse files Browse the repository at this point in the history
…ports

Issue/1427/isort shouldnt move import comments
  • Loading branch information
timothycrosley committed Aug 30, 2020
2 parents d4defa9 + ae10a3f commit 281dfbc
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 8 deletions.
12 changes: 10 additions & 2 deletions isort/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ def _with_from_imports(
if "*" in from_imports and config.combine_star:
import_statement = wrap.line(
with_comments(
comments,
_with_star_comments(parsed, module, list(comments or ())),
f"{import_start}*",
removed=config.ignore_comments,
comment_prefix=config.comment_prefix,
Expand Down Expand Up @@ -364,7 +364,7 @@ def _with_from_imports(
if "*" in from_imports:
output.append(
with_comments(
comments,
_with_star_comments(parsed, module, list(comments or ())),
f"{import_start}*",
removed=config.ignore_comments,
comment_prefix=config.comment_prefix,
Expand Down Expand Up @@ -529,3 +529,11 @@ def is_comment(line):
new_output.append("")
new_output.append(line)
return new_output


def _with_star_comments(parsed: parse.ParsedContent, module: str, comments: List[str]) -> List[str]:
star_comment = parsed.categorized_comments["nested"].get(module, {}).pop("*", None)
if star_comment:
return comments + [star_comment]
else:
return comments
7 changes: 1 addition & 6 deletions isort/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,12 +222,7 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte
import_string, comment = parse_comments(line)
comments = [comment] if comment else []
line_parts = [part for part in _strip_syntax(import_string).strip().split(" ") if part]
if (
type_of_import == "from"
and len(line_parts) == 2
and line_parts[1] != "*"
and comments
):
if type_of_import == "from" and len(line_parts) == 2 and comments:
nested_comments[line_parts[-1]] = comments[0]

if "(" in line.split("#", 1)[0] and index < line_count:
Expand Down
13 changes: 13 additions & 0 deletions tests/unit/test_regressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -632,3 +632,16 @@ def test_isort_should_be_able_to_add_independent_of_doc_string_placement_issue_1
show_diff=True,
add_imports=["os"],
)


def test_comments_should_never_be_moved_between_imports_issue_1427():
"""isort should never move comments to different import statement.
See: https://github.com/PyCQA/isort/issues/1427
"""
assert isort.check_code(
"""from package import CONSTANT
from package import * # noqa
""",
force_single_line=True,
show_diff=True,
)

0 comments on commit 281dfbc

Please sign in to comment.