Accessing source code of object in python🐍

Keerti Prajapati
1 min readDec 20, 2020

As we know, everything in python is an object, even function we define is also an object in Python. As a programmer, we write so many functions and also do use functions written by others.

When we define the function, we know what is written in function and how exactly it works, but when we use functions of other module we don’t know what’s the source code of it.

In this short article, you will learn method to get source code of functions in python.

To get the source code of functions in python, use inspect module. Inspect module have a set of functions using which you can get source code, documentation string, and path of file where method is defined.

Let’s understand it with simple example:

import inspect
import random
print(inspect.getsource(random.randint))

Output:

def randint(self, a, b):
"""Return random integer in range [a, b], including both end points.
"""
return self.randrange(a, b+1)

But one thing to keep in mind, inspect won’t return the source code of built-in objects and object defined interactively.

To get the code of object defined interactively you can use dill.source.getsource function.

Built-in methods of python is written in C and can only be access by directly looking into python source code.

--

--