Skip to content

Instantly share code, notes, and snippets.

@ftnext
Last active May 13, 2024 13:17
Show Gist options
  • Save ftnext/4da27607829a9b18aff928ad85743cd5 to your computer and use it in GitHub Desktop.
Save ftnext/4da27607829a9b18aff928ad85743cd5 to your computer and use it in GitHub Desktop.
『引数の型ヒントをlistにしてはいけません』
import ast
class ArgumentConcreteTypeHintChecker(ast.NodeVisitor):
def visit_arg(self, node):
annotation = node.annotation
if annotation.value.id in {"list", "dict", "set", "tuple"}:
print(f"Fix at {node.lineno}:{node.col_offset}")
print(ast.dump(node))
self.generic_visit(node)
code = """\
from collections.abc import Iterable
print("Hello, world!")
def plus_one_ng(numbers: list[int]) -> list[int]:
return [n + 1 for n in numbers]
def plus_one_ok(numbers: Iterable[int]) -> list[int]:
return [n + 1 for n in numbers]
"""
tree = ast.parse(code)
ArgumentConcreteTypeHintChecker().visit(tree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment