How to retrieve source code from Python objects?


Using the inspect module, you can retrieve the source code of a Python function, method, class, or module. The following example demonstrates how to retrieve a function's source code −

Example

import inspect
def my_function(x, y):
   return x + y
source_code = inspect.getsource(my_function)
print(source_code)

Output

def my_function(x, y):
   return x + y

This code defines a simple function my_function that accepts two arguments and returns the sum of those arguments. We then retrieve the source code of the my_function function using the inspect.getsource() function and store it in the source code variable. Finally, the source code is output to the console.

The inspect.getsource() function operates by reading the function's source code from the file in which it is defined. It returns the function's entire source code as a string, including any comments or blank lines present in the source code.

The inspect.getsourcefile() function can also be used to retrieve the filename containing the source code of a function or module. This is helpful if you need to locate the file containing a specific function or module.

The following example demonstrates how to retrieve the file name containing a function's source code −

Example

import inspect
def my_function(x, y):
   return x + y
source_file = inspect.getsourcefile(my_function)
print(source_file)

Output

/home/cg/root/79120/main.py

This code defines the same my function function as before and retrieves the file name containing the function's source code using the inspect.getsourcefile() function. This function returns the file name as a string, and not the actual source code.

The inspect module offers several functions for retrieving information about Python objects, including their source code. Here are some additional examples −

To retrieve the source code of a class method, call inspect.getsource() on the method itself −

Example

import inspect
class MyClass:
   def my_method(self, x, y):
      return x + y
source_code = inspect.getsource(MyClass.my_method)
print(source_code)

Output

def my_method(self, x, y):
   return x + y

In this example, the class MyClass has a single method called my method that accepts two arguments and returns their sum. The source code for the MyClass.my method method is then retrieved using inspect.getsource().

To retrieve the source code of a module in its entirety, use the inspect.getsource() function on the module itself −

Example

import inspect
import my_module
source_code = inspect.getsource(my_module)
print(source_code)

In this example, we import the my module module and retrieve its source code using inspect.getsource.

You can also use the inspect.getfile function to get the name of the file that holds the source code for a module, class, or function. Similar to inspect.getsourcefile, this function returns the filename as a string. This example demonstrates how to retrieve the filename of a module using inspect.getfile −

Example

import inspect
import my_module
source_file = inspect.getfile(my_module)
print(source_file)

This code imports the my_module module and uses inspect.getfile() to retrieve the source code file's name. Note that this function returns the file's absolute path.

The dis module is another way to retrieve the source code of a Python function. The dis module gives you a disassembler for Python bytecode, which you can use to look at the bytecode instructions for a function. By decompiling the bytecode, it is possible to gain a more comprehensive understanding of how the function operates, including the exact order of operations.

Here is an example of how to retrieve the bytecode instructions of a function using the dis module −

Example

import dis
def my_function(x, y):
   return x + y
bytecode = dis.Bytecode(my_function)
for instruction in bytecode:
   print(instruction)

Output

Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='x', argrepr='x', offset=0, starts_line=3, is_jump_target=False)
Instruction(opname='LOAD_FAST', opcode=124, arg=1, argval='y', argrepr='y', offset=2, starts_line=None, is_jump_target=False)
Instruction(opname='BINARY_ADD', opcode=23, arg=None, argval=None, argrepr='', offset=4, starts_line=None, is_jump_target=False)
Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=6, starts_line=None, is_jump_target=False)

In this example, a simple function called my_function is defined that accepts two arguments and returns their sum. A dis.Bytecode object is then created by passing the my_function function to the dis.Bytecode function Object() { [native code] } . This gives us a view of the function's bytecode instructions after they have been taken apart. We can then use a for loop to go through these instructions and print them to the console.

This code will return a series of dis.Instruction objects, which represent the function's bytecode instructions. Each dis.Instruction object includes attributes such as opname (the name of the bytecode instruction), argval (the instruction's argument), and offset (the byte offset of the instruction in the function's bytecode). By looking at these attributes, you can learn everything you need to know about how the function works.

Please be aware that the dis module can be quite low-level and may not be appropriate for all use cases. However, if you need a thorough understanding of how a function operates, it can be a useful tool to have. We use the getsource() method of the inspect module to get the source code of the function.

Example

inspect.getsource(object)

This returns the text of the object's source code. It is possible for the argument to be a module, class, method, function, traceback, frame, or code object. Returns the source code as a single string. If it is not possible to retrieve the source code, an IOError is generated.

If the function is compiled from a string, stream, or imported from a previously compiled file, then its source code cannot be retrieved.

Following is how we import the inspect module and retrieve the source code for a given script

Example

#baz.py
import inspect
class foo:
   def bar():
      print ('Hello')
print(inspect.getsource(foo))

Output

class foo:
   def bar():
      print ('Hello')

Updated on: 31-Aug-2023

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements