Suppose I have a Python function as defined below:
def foo(arg1,arg2):#do something with argsa = arg1 + arg2return a
#do something with args
a = arg1 + arg2
I can get the name of the function using foo.func_name. How can I programmatically get its source code, as I typed above?
To get the of your function you programmatically you can use the inspect module which has methods for retrieving the source code from python objects. One thing to note it would only work if the source is located in the same file where you are writing the below-mentioned code. Below is the code that shows how to use the inspect module:-
import inspectlines = inspect.getsource(foo)print(lines)
lines = inspect.getsource(foo)