Skip to content

Commit

Permalink
[refactor] Extract ast.Subscript boolean logic
Browse files Browse the repository at this point in the history
* fix: Python 3.9 doesn't have typing.TypeGuard
  • Loading branch information
ftnext committed Oct 15, 2024
1 parent fc3825e commit ed8f58a
Showing 1 changed file with 18 additions and 17 deletions.
35 changes: 18 additions & 17 deletions src/kotoha/core.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import ast
from typing import TypeGuard
from typing import cast

KTH101 = (
"KTH101 "
Expand Down Expand Up @@ -41,25 +41,26 @@ def __init__(self) -> None:
self.errors: list[tuple[LineNumber, ColumnOffset, ErrorMessage]] = []

@staticmethod
def is_annotated(annotation: ast.expr | None) -> TypeGuard[ast.expr]:
return annotation is not None
def is_annotated_with_subscript(arg: ast.arg) -> bool:
if arg.annotation is None:
return False
# arg.annotation(: ast.expr) is
# ast.Name, ast.Subscript or ast.Attribute.
return isinstance(arg.annotation, ast.Subscript)

def visit_arg(self, node: ast.arg) -> None:
if self.is_annotated(node.annotation):
# node.annotations is ast.Name, ast.Subscript or ast.Attribute
if isinstance(node.annotation, ast.Subscript):
value_node = node.annotation.value
assert isinstance(value_node, ast.Name)
if value_node.id in self._concrete_type_hint_error_codes:
self.errors.append(
(
node.lineno,
node.col_offset,
self._concrete_type_hint_error_codes[
value_node.id
],
)
if self.is_annotated_with_subscript(node):
annotation = cast(ast.Subscript, node.annotation)
value_node = annotation.value
assert isinstance(value_node, ast.Name)
if value_node.id in self._concrete_type_hint_error_codes:
self.errors.append(
(
node.lineno,
node.col_offset,
self._concrete_type_hint_error_codes[value_node.id],
)
)
self.generic_visit(node)


Expand Down

0 comments on commit ed8f58a

Please sign in to comment.