0 votes
1 view
in Python by (47.8k points)

Suppose I have a Python function as defined below:

def foo(arg1,arg2):

#do something with args

a = arg1 + arg2

return a

I can get the name of the function using foo.func_name. How can I programmatically get its source code, as I typed above?

1 Answer

0 votes
by (107k points)

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 inspect

lines = inspect.getsource(foo)

print(lines)

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...