Assume that I have a python source file, the names of a specific class and a from this file, and a string to replace the body of that function. How can I write a program to do this automatically? I am not looking for “string”-matching solutions. I am mostly looking for a python library that might facilitate this task.
To clarify, the main challenge I am facing is: “How to locate the said class/function since it can be nested like class/function/function, or many other ways”
Here is an example:
INPUT:
JavaScript
x
20
20
1
# old.py
2
class C:
3
def f1():
4
# body_stmts_f1
5
6
def g1(j):
7
a = 10
8
b = 30
9
return a + b * j
10
11
12
# class/function of interest: C, g1
13
14
15
# new_g1_body.py
16
def g1(j):
17
a = 40
18
x = 100
19
return a - x + j
20
OUTPUT:
JavaScript
1
9
1
class C:
2
def f1():
3
# body_stmts_f1
4
5
def g1(j):
6
a = 40
7
x = 100
8
return a - x + j
9
Advertisement
Answer
I ended up using Python’s own AST package. First, I parse
the original file, then I find the function that I want to change using visitors
, then I make the desired changes to that function. Finally, I unparse
the modified AST.