Skip to content

Commit

Permalink
is_type_comment now checks for extra or zero spaces (psf#2097)
Browse files Browse the repository at this point in the history
  • Loading branch information
Pedro-Muller29 committed Sep 27, 2024
1 parent bbfdba3 commit 4e9abef
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/black/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
blib2to3 Node/Leaf transformation-related utility functions.
"""

import re
import sys
from typing import Final, Generic, Iterator, Literal, Optional, TypeVar, Union

Expand Down Expand Up @@ -911,7 +912,10 @@ def is_type_comment(leaf: Leaf) -> bool:
used in modern version of Python, this function may be deprecated in the future."""
t = leaf.type
v = leaf.value
return t in {token.COMMENT, STANDALONE_COMMENT} and v.startswith("# type:")
return (
t in {token.COMMENT, STANDALONE_COMMENT}
and bool(re.match(r"#\s*type:", v))
)


def is_type_ignore_comment(leaf: Leaf) -> bool:
Expand Down
28 changes: 28 additions & 0 deletions tests/test_nodes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""Test the black.nodes module."""

import pytest

from black import Leaf, token
from black.nodes import is_type_comment


@pytest.mark.parametrize(
"comment_text, expected",
[
("# type: int", True),
("#type:int", True),
("# type: str", True),
("# type :List[int]", False),
("# type : Dict[str, Any]", False),
("#type :", False),
("#type: ", True),
("#", False),
("# some other comment type: ", False),
("# type", False),
("# type:", True),
("# type :", False),
],
)
def test_is_type_comment(comment_text: str, expected: bool) -> None:
leaf = Leaf(token.COMMENT, comment_text)
assert is_type_comment(leaf) == expected

0 comments on commit 4e9abef

Please sign in to comment.