diff --git a/isort/output.py b/isort/output.py index 7d793ac1e..1a6c504b6 100644 --- a/isort/output.py +++ b/isort/output.py @@ -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, @@ -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, @@ -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 diff --git a/isort/parse.py b/isort/parse.py index 1e71c6d2c..913cdbb12 100644 --- a/isort/parse.py +++ b/isort/parse.py @@ -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: diff --git a/tests/unit/test_regressions.py b/tests/unit/test_regressions.py index eb10dc819..3b35c4016 100644 --- a/tests/unit/test_regressions.py +++ b/tests/unit/test_regressions.py @@ -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, + )