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: Retrieve Function Source Code

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.

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

Example: Get Filename Containing a Function

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

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.

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

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

Example: Retrieve Source Code of a Class Method

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

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().

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

Example: Retrieve Source Code of a Module

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

In this example, we create a simple module named my_module containing a basic function. Then, from another script, we import this module and retrieve its source code using inspect.getsource() function ?

Step 1: Create the module my_module.py

# my_module.py

def greet(name):
   return f"Hello, {name}!"

Step 2: Retrieve the source code in another script

# main.py

import inspect
# Ensure this file is in the same directory
import my_module  

# Retrieve and print the full source code of the module
source_code = inspect.getsource(my_module)
print(source_code)

We will get the output as shown below ?

def greet(name):
   return f"Hello, {name}!"

Example: Get File Path of a Module

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 -

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

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

We get the output as shown below ?

/full/path/to/my_module.py

Using the dis Module

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.

Example: View Bytecode Instructions

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

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.

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

This code will return a series of dis.Instruction objects 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.

Instruction(opname='RESUME', opcode=151, arg=0, argval=0, argrepr='', offset=0, starts_line=2, is_jump_target=False, positions=Positions(lineno=2, end_lineno=2, col_offset=0, end_col_offset=0))
Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='x', argrepr='x', offset=2, starts_line=3, is_jump_target=False, positions=Positions(lineno=3, end_lineno=3, col_offset=10, end_col_offset=11))
Instruction(opname='LOAD_FAST', opcode=124, arg=1, argval='y', argrepr='y', offset=4, starts_line=None, is_jump_target=False, positions=Positions(lineno=3, end_lineno=3, col_offset=14, end_col_offset=15))
Instruction(opname='BINARY_OP', opcode=122, arg=0, argval=0, argrepr='+', offset=6, starts_line=None, is_jump_target=False, positions=Positions(lineno=3, end_lineno=3, col_offset=10, end_col_offset=15))
Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=10, starts_line=None, is_jump_target=False, positions=Positions(lineno=3, end_lineno=3, col_offset=3, end_col_offset=15))
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: General Usage of inspect.getsource()

The following code 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.

inspect.getsource(object)

Example: Get Source Code of a Class in Script

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

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

Output

class foo:
   def bar():
      print ('Hello')
Updated on: 2025-04-11T14:50:14+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements