Skip to content
Related Articles

Related Articles

How to retrieve source code from Python objects?
  • Last Updated : 29 Aug, 2020

It is sometimes important to know what some functions source codes look like. In such cases, we have inspect module a built-in standard library in Python programming. It provides 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)

Return type: text of the source code for an object

An IOError is raised if the source code cannot be retrieved.

Example:



filter_none

edit
close

play_arrow

link
brightness_4
code

# import inspect library
import inspect
  
def test(x):
    return x * 2
  
print(inspect.getsource(test))

chevron_right


Output:

def test(x):

   return (x+2)*(x-2)

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# import inspect library
import inspect
import pandas
  
  
source_DF = inspect.getsource(pandas.DataFrame)
print(source_DF[:100])

chevron_right


Output:

class DataFrame(NDFrame):
    """
    Two-dimensional size-mutable, potentially heterogeneous tabula

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :