我希望找到所有返 echo 式元组的函数. 例如,
...
return x, y
会很流行,但是
...
return {"x":x, "y":y}
将不存在,因此regexp搜索return .*,
将返回太多的误报.
我怀疑pylint
/astroid
可能会做我想要的事情,但我对all条建议持开放态度.
PS.没有类型注释--我宁愿让某个东西自动生成它们,就像在ocaml
中一样.
我希望找到所有返 echo 式元组的函数. 例如,
...
return x, y
会很流行,但是
...
return {"x":x, "y":y}
将不存在,因此regexp搜索return .*,
将返回太多的误报.
我怀疑pylint
/astroid
可能会做我想要的事情,但我对all条建议持开放态度.
PS.没有类型注释--我宁愿让某个东西自动生成它们,就像在ocaml
中一样.
这是一个可以做你想做的事情的Pylt插件.
from astroid import nodes
from pylint.checkers import BaseChecker
class TupleReturnChecker(BaseChecker):
msgs = {
"W5100": (
"Tuple in return %s",
"tuple-in-return",
"Raised when a tuple is returned.",
)
}
def visit_return(self, node: nodes.Return) -> None:
if isinstance(node.value, nodes.Tuple):
self.add_message("tuple-in-return", args=node.as_string())
但在这个简单的例子中,你不需要使用星体,ast.NodeVisitor
看起来会很相似.
import ast
class TupleDetector(ast.NodeVisitor):
def visit_Return(self, node: ast.Return) -> None:
if isinstance(node.value, ast.Tuple):
print(f"{node} is a tuple")
detector = TupleDetector()
with open(code_path) as f:
detector.visit(ast.parse(f.read()))
如果您有一些东西可能返回一个元组,并且您需要进行推理,则pylint将非常有用.