Skip to content
Advertisement

Replacing the body of a specific function in python code

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:

# old.py
class C:
  def f1():
    # body_stmts_f1

  def g1(j):
    a = 10
    b = 30
    return a + b * j


# class/function of interest: C, g1


# new_g1_body.py
  def g1(j):
    a = 40
    x = 100
    return a - x + j

OUTPUT:

class C:
  def f1():
    # body_stmts_f1

  def g1(j):
    a = 40
    x = 100
    return a - x + j

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement