pythonrefactoringpylintastroid

Python: How do I find all functions that return tuples explicitly?


I would like to find all functions that return an explicit tuple. E.g.,

    ...
    return x, y

would be in, but

    ...
    return {"x":x, "y":y}

would be out, so regexp searching for return .*, would return too many false positives.

I suspect that pylint/astroid might do what I want, but I am open to all suggestions.

PS. There are no type annotations - I would rather have something generate them automatically, like in ocaml.


Solution

  • Here's a pylint plugin that does what you want.

    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())
    

    But you don't need to use astroid/pylint for that simple case, an ast.NodeVisitor would looks pretty much the same.

    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 would be useful if you have something possibly returning a tuple and you need inference.