Skip to content Skip to sidebar Skip to footer

Using AST To Change Function Names From CamelCase To Snake_case

Here in this question, I was asking for a way to convert function names from CamelCase to snake_case, one of the comments suggested using AST. I found a code snippet to find all fu

Solution 1:

I am kind of late to this, but maybe it will be found in the future.

Anyway, here is a quick hack at it. Actually, you were almost there with your solution. The name method returns your name, then you can arbitrarily change that. So in your def get_func_calls(tree) call you can manipulate the string and re-assign the new name to the Call object.

ccName = callvisitor.name # work with some local var
new_name = ''             # the new func name
for char_i in range(len(ccName)): # go over the name
    if ccName[char_i].isupper():  # check if the current char is with uppercase
        if ccName[char_i - 1] == '.': # check if the previous character is a dot
            new_name += ccName[char_i].lower() # if it is, make the char to lowercase
        else:
            new_name += '_' + ccName[char_i].lower() # otherwise add the snake_
    else:
        new_name += ccName[char_i] # just add the rest of the lower chars
callvisitor._name = new_name       # just re-asign the new name 
func_calls.append(callvisitor._name)

This is definitely not a pretty solution and it also depends if you want to change only function definitions or every single function call in a file, but this should give you an idea on how to change the ast.


Post a Comment for "Using AST To Change Function Names From CamelCase To Snake_case"