From 31a31d0ec43ee083e3f5ad5a4cfcfea8e0b93616 Mon Sep 17 00:00:00 2001 From: Timothy Crosley Date: Thu, 16 Jan 2020 22:41:59 -0800 Subject: Fix issue #1103 --- isort/api.py | 1 + isort/parse.py | 4 ++-- tests/test_isort.py | 10 ++++++++++ 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/isort/api.py b/isort/api.py index 41a919b6..3d34d835 100644 --- a/isort/api.py +++ b/isort/api.py @@ -233,6 +233,7 @@ def sort_imports( new_indent = line[: -len(line.lstrip())] import_statement = line + stripped_line = line.strip().split("#")[0] while stripped_line.endswith("\\") or ( "(" in stripped_line and ")" not in stripped_line ): diff --git a/isort/parse.py b/isort/parse.py index 09e381be..d007d43d 100644 --- a/isort/parse.py +++ b/isort/parse.py @@ -211,7 +211,7 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte nested_comments[line_parts[-1]] = comments[0] if "(" in line.split("#")[0] and index < line_count: - while not line.strip().endswith(")") and index < line_count: + while not line.split("#")[0].strip().endswith(")") and index < line_count: line, new_comment = parse_comments(in_lines[index]) index += 1 if new_comment: @@ -248,7 +248,7 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte nested_comments[stripped_line] = comments[-1] import_string += line_separator + line - while not line.strip().endswith(")") and index < line_count: + while not line.split("#")[0].strip().endswith(")") and index < line_count: line, new_comment = parse_comments(in_lines[index]) index += 1 if new_comment: diff --git a/tests/test_isort.py b/tests/test_isort.py index 8cabcce2..e4c61c3d 100644 --- a/tests/test_isort.py +++ b/tests/test_isort.py @@ -4818,3 +4818,13 @@ import datetime as dt2 assert ( SortImports(keep_direct_and_as_imports=True, file_contents=test_input).output == test_input ) + + +def test_parens_in_comment(): + """Test to ensure isort can handle parens placed in comments. See issue #1103""" + test_input = """from foo import ( # (some text in brackets) + bar, +) +""" + expected_output = "from foo import bar # (some text in brackets)\n" + assert SortImports(file_contents=test_input).output == expected_output -- cgit v1.2.1