diff --git a/ast_comments.py b/ast_comments.py index 4947603..809bfa4 100644 --- a/ast_comments.py +++ b/ast_comments.py @@ -196,6 +196,8 @@ def _extend_interval(interval: _t.Tuple[int, int], code: str) -> _t.Tuple[int, i # In each block there must be at least one, otherwise the code is not valid def _get_first_line_not_comment(lines: _t.List[str]): for line in lines: + if not line.strip(): + continue if not re.match(r"^ *#.*", line): return line return "" diff --git a/test_parse.py b/test_parse.py index 3ec6d9b..e85f8f3 100644 --- a/test_parse.py +++ b/test_parse.py @@ -356,6 +356,23 @@ def test_comment_to_multiline_expr(): assert body_nodes[1].inline +def test_empty_line_not_affect_comment_placement(): + """Empty line doesn't mess with indendation intervals.""" + source = dedent( + """ + # comment 1 + if a: # comment 2 + + pass + """ + ) + body = parse(source).body + assert len(body) == 2 + assert isinstance(body[0], Comment) + if_body = body[1].body + assert isinstance(if_body[0], Comment) + + @pytest.mark.xfail(reason="https://github.com/t3rn0/ast-comments/issues/13") def test_comment_in_multilined_list(): """Comment to element of the list stays inside the list.""" diff --git a/test_unparse.py b/test_unparse.py index 892711b..399ccee 100644 --- a/test_unparse.py +++ b/test_unparse.py @@ -233,6 +233,19 @@ def test_comment_to_multiline_expr(): _test_unparse(source) +def test_empty_line_not_affect_comment_placement(): + """Empty line doesn't mess with indendation intervals.""" + source = dedent( + """ + # comment 1 + if a: # comment 2 + + pass + """ + ) + _test_unparse(source) + + @pytest.mark.xfail(reason="https://github.com/t3rn0/ast-comments/issues/13") def test_comment_in_multilined_list(): source = dedent(