Sometimes, we want to get the source code of a Python function.
In this article, we’ll look at how to get the source code of a Python function.
How to get the source code of a Python function?
To get the source code of a Python function, we can use the inspect.getsource
method.
For instance, we write:
import inspect
def foo(arg1, arg2):
a = arg1 + arg2
return a
lines = inspect.getsource(foo)
print(lines)
We create the foo
function that we want to get the code for into a string.
To do that, we call inspect.getsource
with foo
and assign the code string to lines
.
Therefore, lines
is:
def foo(arg1, arg2):
a = arg1 + arg2
return a
Conclusion
To get the source code of a Python function, we can use the inspect.getsource
method.