From 67119b9de7f669d6b9e84ede3aafc82bc5627430 Mon Sep 17 00:00:00 2001 From: Pedro Mezacasa Muller Date: Thu, 26 Sep 2024 22:52:49 -0300 Subject: [PATCH] is_type_comment now checks for extra or zero spaces (#2097) --- src/black/nodes.py | 6 +++++- tests/test_nodes.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 tests/test_nodes.py diff --git a/src/black/nodes.py b/src/black/nodes.py index 470dc248488..28598a5d5fd 100644 --- a/src/black/nodes.py +++ b/src/black/nodes.py @@ -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 @@ -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: diff --git a/tests/test_nodes.py b/tests/test_nodes.py new file mode 100644 index 00000000000..a206f6947ae --- /dev/null +++ b/tests/test_nodes.py @@ -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