How to use the inspect module to retrieve source code In Python
Example: Here we are importing the inspect module first and then using the inspect.getsource() function to fetch the source code of the given object.
python3
# import inspect library import inspect def test(x): return x * 2 print (inspect.getsource(test)) |
Output:
def test(x): return (x+2)*(x-2)
Example: Here we are fetching the source code for the given object.
python3
# import inspect library import inspect def far(n): factorial = 1 if int (n) > = 1 : for i in range ( 1 , int (n) + 1 ): factorial = factorial * i return factorial source = inspect.getsource(far) print (source) |
Output:
def far(n): factorial = 1 if int(n) >= 1: for i in range (1, int(n)+1): factorial = factorial * i return factorial
Example: We can use inspect on built in library functions and objects also.
python3
# import inspect library import inspect import pandas source_DF = inspect.getsource(pandas.DataFrame) print (source_DF[: 100 ]) |
Output:
class DataFrame(NDFrame): """ Two-dimensional size-mutable, potentially heterogeneous tabula
How to retrieve source code from Python objects?
We are given a object and our task is to retrieve its source code, for this we have inspect module, dill module and dis module built-in standard libraries in Python programming. They provide several useful functions to track information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. getsource() method is used to get the source code of Python objects.
Syntax: inspect.getsource(object)
Parameter: The object type parameter, of which we want the source code.
Return type: text of the source code for an object
Note: An IOError is raised if the source code cannot be retrieved.
Contact Us