Python inspect module

Filed Under: Python
Python Inspect Module

Python inspect module

Python inspect module is a very useful module which is used to introspect live objects in a program and look at the source code of modules, classes and functions which are used throughout a program. This is powerful because this module can actually be used to extract the source code of a function itself, parse the arguments which that function accepts and related library documentation.

Providing sample module

To take a sample to be used throughout this lesson, we will construct a very small sample module with some functions, classes and Python docstrings. Here is the code snippet for sample.py:


def module_funct(arg1, arg2 = 'default', *args):
    """This is a module-level function."""
    local_var = arg1 * 3
    return local_var

class X(object):
    """Definition for X class."""

    def __init__(self, name):
        self.name = name

    def get_name(self):
        "Returns the name of the instance."
        return self.name

x_obj = X('sample_instance')

class Y(X):
    """This is the Y class, 
    child of X class.
    """

    # This method is not part of X class.
    def do_something(self):
        """Anything can be done here."""

    def get_name(self):
        "Overrides version from X"
        return 'Y(' + self.name + ')'

Now that we have a sample module ready for usage, we can start extract and introspecting its source code, docstring and object details. Let’s get started.

Introspecting module

Let us start by introspecting the sample module we defined. Note that for this, we have the sample module file sample.py in the same directory as we execute our scripts in. Here is a sample code snippet on how we can inspect our module:


import inspect
import sample

for name, data in inspect.getmembers(sample):
    if name.startswith('__'):
        continue
    print('{} : {!r}'.format(name, data))

Let’s see the output for this program:

python inspect module

Introspecting module with inspect

Introspecting classes in a module

We can get all the classes which are present in a module and take action when we find the class we were looking for:


import inspect
import sample

for key, data in inspect.getmembers(sample, inspect.isclass):
    print('{} : {!r}'.format(key, data))

Let’s see the output for this program:

python inspect class

Introspecting module classes with inspect


With a simple identification with the help of isclass property, we were able to get the classes of the modules.

Introspecting methods in a classes

This time, we go deeper by inspecting the methods which are present in a class. Notice that we use the same method getmembers and only the property identifier is different, i.e. isfunction:


import inspect
from pprint import pprint
import sample

pprint(inspect.getmembers(sample.X, inspect.isfunction))

Let’s see the output for this program:

python inspect methods

Introspecting methods of a class

Introspecting objects of a class

With the inspect module, it is possible to keep track of all the instances of a class made in a program simply with a single function call:


import inspect
from pprint import pprint
import sample

x = sample.X(name='inspect_getmembers')
pprint(inspect.getmembers(x, inspect.ismethod))

Let’s see the output for this program:

python inspect example objects

Inspecting objects of a class

Getting Docstring for class

inspect module is often used in Python tools which automate the process of extracting a class and their methods docstrings which can be presented to end-users. This means that a developer can simply put docstrings in a method and the same docstring can be used to be presented to another developer of the application as well which reduces developer effort:


import inspect
import sample

print('X.__doc__:')
print(sample.X.__doc__)
print()
print('getdoc(X):')
print(inspect.getdoc(sample.X))

Let’s see the output for this program:
python inspect getdoc example

Getting Source of class

In intelligent environments like an IDE, inspect module is used to present the source code of modules, classes, and functions:


import inspect
import sample

print(inspect.getsource(sample.Y))

Let’s see the output for this program:

python inspect source code

Getting Source code of a class


Complete source code of the class was printed for the class without any docstring.

Getting Source of method

This time, we get teh source code of a single method only:


import inspect
import sample

print(inspect.getsource(sample.Y.get_name))

Let’s see the output for this program:

python inspect source method

Getting Source code of a method

Getting Method Signature

For a final example, we will get the signature of a method which is used a lot in Intellisense of an IDEs to present to developers what arguments does a method accepts:


import inspect
import sample

print(inspect.signature(sample.module_funct))

Let’s see the output for this program:

python inspect signature

Getting Signature of method

Conclusion

In this lesson, we studied an excellent Python module, inspect which is used a lot in Code tools like IDEs and documentation tools as well.

Reference: API Doc.

Comments

  1. manjula arjun says:

    Real usefull article!!!!

  2. Dan says:

    Hi thanks for the great article, as I was working through it I found a typo in the “Introspecting methods in a classes” section the example code is “pprint(inspect.getmembers(sample.X, inspect.isfunction))” but it should be “pprint(inspect.getmembers(sample.X, inspect.ismethod)) ” since you were looking for the class methods.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages