Skip to content

Commit ed8f58a

Browse files
committed
[refactor] Extract ast.Subscript boolean logic
* fix: Python 3.9 doesn't have typing.TypeGuard
1 parent fc3825e commit ed8f58a

File tree

1 file changed

+18
-17
lines changed

1 file changed

+18
-17
lines changed

src/kotoha/core.py

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import ast
2-
from typing import TypeGuard
2+
from typing import cast
33

44
KTH101 = (
55
"KTH101 "
@@ -41,25 +41,26 @@ def __init__(self) -> None:
4141
self.errors: list[tuple[LineNumber, ColumnOffset, ErrorMessage]] = []
4242

4343
@staticmethod
44-
def is_annotated(annotation: ast.expr | None) -> TypeGuard[ast.expr]:
45-
return annotation is not None
44+
def is_annotated_with_subscript(arg: ast.arg) -> bool:
45+
if arg.annotation is None:
46+
return False
47+
# arg.annotation(: ast.expr) is
48+
# ast.Name, ast.Subscript or ast.Attribute.
49+
return isinstance(arg.annotation, ast.Subscript)
4650

4751
def visit_arg(self, node: ast.arg) -> None:
48-
if self.is_annotated(node.annotation):
49-
# node.annotations is ast.Name, ast.Subscript or ast.Attribute
50-
if isinstance(node.annotation, ast.Subscript):
51-
value_node = node.annotation.value
52-
assert isinstance(value_node, ast.Name)
53-
if value_node.id in self._concrete_type_hint_error_codes:
54-
self.errors.append(
55-
(
56-
node.lineno,
57-
node.col_offset,
58-
self._concrete_type_hint_error_codes[
59-
value_node.id
60-
],
61-
)
52+
if self.is_annotated_with_subscript(node):
53+
annotation = cast(ast.Subscript, node.annotation)
54+
value_node = annotation.value
55+
assert isinstance(value_node, ast.Name)
56+
if value_node.id in self._concrete_type_hint_error_codes:
57+
self.errors.append(
58+
(
59+
node.lineno,
60+
node.col_offset,
61+
self._concrete_type_hint_error_codes[value_node.id],
6262
)
63+
)
6364
self.generic_visit(node)
6465

6566

0 commit comments

Comments
 (0)