Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k 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 (106k 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)

Browse Categories

...