Search code examples
pythonabstract-syntax-tree

How to rename all variables according to rule set with AST


Is there a tool that is capable of iterating over all variables and function arguments in a Python file and replace them according to a style rule? For example, given a function in myModule.py

def myFunc(Variable):
    Tmp = sin(Variable)
    return Tmp * 2

Is there a tool that could be called in a manner like the following

> tool myModule.py --variable-begin-with-lowercase

to produce the result below?

def myFunc(variable):
    tmp = sin(variable)
    return tmp * 2

I suppose, that the tool should warn about renamings that interfere with existing variables.


Solution

  • You can use ast.NodeTransformer:

    import ast
    
    class toLower(ast.NodeTransformer):
        def visit_arg(self, node):
            return ast.arg(**{**node.__dict__, 'arg':node.arg.lower()})
    
        def visit_Name(self, node):
            return ast.Name(**{**node.__dict__, 'id':node.id.lower()})
    
    code = """
    def myFunc(Variable):
        Tmp = sin(Variable)
        return Tmp * 2
    """
    new_code = ast.unparse(toLower().visit(ast.parse(code)))
    print(new_code)
    

    Output:

    def myFunc(variable):
        tmp = sin(variable)
        return tmp * 2