Skip to content
Related Articles

Related Articles

Improve Article

Inspect Module in Python

  • Last Updated : 17 Dec, 2020

The inspect module helps in checking the objects present in the code that we have written. As Python is an OOP language and all the code that is written is basically an interaction between these objects, hence the inspect module becomes very useful in inspecting certain modules or certain objects. We can also use it to get a detailed analysis of certain function calls or tracebacks so that debugging can be easier.

The inspect module provides a lot of methods, these methods can be classified into two categories i.e. methods to verify the type of token and methods to retrieve the source of token. The most commonly used methods of both categories are mentioned below.

Methods to verify the type of token:

  • isclass(): The isclass() method returns True if that object is a class or false otherwise. When it is combined with the getmembers() functions it shows the class and its type. It is used to inspect live classes.

Example:

Python3




# import required modules
import inspect
  
# create class
class A(object):
    pass
  
# use isclass()
print(inspect.isclass(A))

Output:



True
  • ismodule(): This returns true if the given argument is an imported module.

Example:

Python3




# import required modules
import inspect
import numpy
  
# use ismodule()
print(inspect.ismodule(numpy))

Output:

True
  • isfunction(): This method returns true if the given argument is an inbuilt function name.

Example:

Python3




# import required modules
import inspect
  
# explicit function
def fun(a):
    return 2*a
  
# use isfunction()
print(inspect.isfunction(fun))

Output:

True
  • ismethod(): This method is used to check if the argument passed is the name of a method or not.

Example:

Python3






# import required modules
import inspect
import collections
  
# use ismethod()
print(inspect.ismethod(collections.Counter))

Output:

False

Methods to retrieve the source of token:

  • getclasstree(): The getclasstree() method will help in getting and inspecting class hierarchy. It returns a tuple of that class and that of its preceding base classes. That combined with the getmro() method which returns the base classes helps in understanding the class hierarchy.

Example 1:

Python3




# import required module
import inspect
  
# create classes
class A(object):
    pass
  
class B(A):
    pass
  
class C(B):
    pass
  
# not nested
print(inspect.getmro(C))  

Output:

(<class ‘__main__.C’>, <class ‘__main__.B’>, <class ‘__main__.A’>, <class ‘object’>) ‚Äč

Example 2:

Python3




# import required module
import inspect
  
# create classes
class A(object):
    pass
  
class B(A):
    pass
  
class C(B):
    pass
  
# nested list of tuples
for i in (inspect.getclasstree(inspect.getmro(C))):
    print(i)

Output:

(<class ‘object’>, ()) [(<class ‘__main__.A’>, (<class ‘object’>,)), [(<class ‘__main__.B’>, (<class ‘__main__.A’>,)), [(<class ‘__main__.C’>, (<class ‘__main__.B’>,))]]]

  • getmembers(): This method returns the member functions present in the module passed as an argument of this method.

Example:



Python3




# import required module
import inspect
import math
  
# shows the member functions
# of any module or object
print(inspect.getmembers(math))

Output:

[(‘__doc__’, ‘This module provides access to the mathematical functions\ndefined by the C standard.’), (‘__loader__’, <class ‘_frozen_importlib.BuiltinImporter’>), (‘__name__’, ‘math’), (‘__package__’, ”), (‘__spec__’, ModuleSpec(name=’math’, loader=<class ‘_frozen_importlib.BuiltinImporter’>, origin=’built-in’)), (‘acos’, <built-in function acos>), (‘acosh’, <built-in function acosh>), (‘asin’, <built-in function asin>), (‘asinh’, <built-in function asinh>), (‘atan’, <built-in function atan>), (‘atan2’, <built-in function atan2>), (‘atanh’, <built-in function atanh>), (‘ceil’, <built-in function ceil>), (‘copysign’, <built-in function copysign>), (‘cos’, <built-in function cos>), (‘cosh’, <built-in function cosh>), (‘degrees’, <built-in function degrees>), (‘e’, 2.718281828459045), (‘erf’, <built-in function erf>), (‘erfc’, <built-in function erfc>), (‘exp’, <built-in function exp>), (‘expm1’, <built-in function expm1>), (‘fabs’, <built-in function fabs>), (‘factorial’, <built-in function factorial>), (‘floor’, <built-in function floor>), (‘fmod’, <built-in function fmod>), (‘frexp’, <built-in function frexp>), (‘fsum’, <built-in function fsum>), (‘gamma’, <built-in function gamma>), (‘gcd’, <built-in function gcd>), (‘hypot’, <built-in function hypot>), (‘inf’, inf), (‘isclose’, <built-in function isclose>), (‘isfinite’, <built-in function isfinite>), (‘isinf’, <built-in function isinf>), (‘isnan’, <built-in function isnan>), (‘ldexp’, <built-in function ldexp>), (‘lgamma’, <built-in function lgamma>), (‘log’, <built-in function log>), (‘log10’, <built-in function log10>), (‘log1p’, <built-in function log1p>), (‘log2’, <built-in function log2>), (‘modf’, <built-in function modf>), (‘nan’, nan), (‘pi’, 3.141592653589793), (‘pow’, <built-in function pow>), (‘radians’, <built-in function radians>), (‘remainder’, <built-in function remainder>), (‘sin’, <built-in function sin>), (‘sinh’, <built-in function sinh>), (‘sqrt’, <built-in function sqrt>), (‘tan’, <built-in function tan>), (‘tanh’, <built-in function tanh>), (‘tau’, 6.283185307179586), (‘trunc’, <built-in function trunc>)]

  • signature(): The signature() method helps the user in understanding the attributes which are to be passed on to a function.

Python3




# import required modules
import inspect
import collections
  
# use signature()
print(inspect.signature(collections.Counter))

Output:

(*args, **kwds)
  • stack(): This method helps in examining the interpreter stack or the order in which functions were called.

Python3




# import required module
import inspect
  
# define explicit function
def Fibonacci(n):
    if n < 0:
        return 0
  
    elif n == 0:
        return 0
  
    elif n == 1:
        return 1
    else:
        return Fibonacci(n-1)+Fibonacci(n-2)
  
  
# Driver Program
(Fibonacci(12))
  
# inpsecting interpreter stack
print(inspect.stack())

Output:

[FrameInfo(frame=<frame at 0x000002AC9BF9FD18, file ‘<ipython-input-8-3080f52ca090>’, line 22, code <module>>, filename='<ipython-input-8-3080f52ca090>’, lineno=22, function='<module>’, code_context=[‘print(inspect.stack())\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BAABA38, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, line 3331, code run_code>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, lineno=3331, function=’run_code’, code_context=[‘                    exec(code_obj, self.user_global_ns, self.user_ns)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9A94B608, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, line 3254, code run_ast_nodes>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, lineno=3254, function=’run_ast_nodes’, code_context=[‘                    if (await self.run_code(code, result,  async_=asy)):\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BA8D768, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, line 3063, code run_cell_async>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, lineno=3063, function=’run_cell_async’, code_context=[‘                       interactivity=interactivity, compiler=compiler, result=result)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9C452618, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\async_helpers.py’, line 68, code _pseudo_sync_runner>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\async_helpers.py’, lineno=68, function=’_pseudo_sync_runner’, code_context=[‘        coro.send(None)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BEE1778, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, line 2886, code _run_cell>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, lineno=2886, function=’_run_cell’, code_context=[‘            return runner(coro)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BE85FC8, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, line 2858, code run_cell>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, lineno=2858, function=’run_cell’, code_context=[‘                raw_cell, store_history, silent, shell_futures)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9C464208, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\zmqshell.py’, line 536, code run_cell>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\zmqshell.py’, lineno=536, function=’run_cell’, code_context=[‘        return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BECB108, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\ipkernel.py’, line 300, code do_execute>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\ipkernel.py’, lineno=300, function=’do_execute’, code_context=[‘                res = shell.run_cell(code, store_history=store_history, silent=silent)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BF9FAF8, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, line 209, code wrapper>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, lineno=209, function=’wrapper’, code_context=[‘                    yielded = next(result)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BECAEB8, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\kernelbase.py’, line 541, code execute_request>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\kernelbase.py’, lineno=541, function=’execute_request’, code_context=[‘                user_expressions, allow_stdin,\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BF9F6B8, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, line 209, code wrapper>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, lineno=209, function=’wrapper’, code_context=[‘                    yielded = next(result)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BEE1BD8, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\kernelbase.py’, line 268, code dispatch_shell>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\kernelbase.py’, lineno=268, function=’dispatch_shell’, code_context=[‘                yield gen.maybe_future(handler(stream, idents, msg))\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BFA0378, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, line 209, code wrapper>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, lineno=209, function=’wrapper’, code_context=[‘                    yielded = next(result)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9C44A848, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\kernelbase.py’, line 361, code process_one>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\kernelbase.py’, lineno=361, function=’process_one’, code_context=[‘        yield gen.maybe_future(dispatch(*args))\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BE85368, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, line 748, code run>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, lineno=748, function=’run’, code_context=[‘                        yielded = self.gen.send(value)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9C456048, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, line 787, code inner>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, lineno=787, function=’inner’, code_context=[‘                self.run()\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BE882D8, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\ioloop.py’, line 743, code _run_callback>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\ioloop.py’, lineno=743, function=’_run_callback’, code_context=[‘            ret = callback()\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9C4519A8, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\ioloop.py’, line 690, code <lambda>>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\ioloop.py’, lineno=690, function='<lambda>’, code_context=[‘                lambda f: self._run_callback(functools.partial(callback, future))\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BEE5808, file ‘D:\\Software\\Anaconda\\lib\\asyncio\\events.py’, line 88, code _run>, filename=’D:\\Software\\Anaconda\\lib\\asyncio\\events.py’, lineno=88, function=’_run’, code_context=[‘            self._context.run(self._callback, *self._args)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BEC9798, file ‘D:\\Software\\Anaconda\\lib\\asyncio\\base_events.py’, line 1782, code _run_once>, filename=’D:\\Software\\Anaconda\\lib\\asyncio\\base_events.py’, lineno=1782, function=’_run_once’, code_context=[‘                handle._run()\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9C44BB88, file ‘D:\\Software\\Anaconda\\lib\\asyncio\\base_events.py’, line 538, code run_forever>, filename=’D:\\Software\\Anaconda\\lib\\asyncio\\base_events.py’, lineno=538, function=’run_forever’, code_context=[‘                self._run_once()\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9C44B9A8, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\platform\\asyncio.py’, line 153, code start>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\platform\\asyncio.py’, lineno=153, function=’start’, code_context=[‘            self.asyncio_loop.run_forever()\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9C335248, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\kernelapp.py’, line 583, code start>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\kernelapp.py’, lineno=583, function=’start’, code_context=[‘            self.io_loop.start()\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9A980F38, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\traitlets\\config\\application.py’, line 664, code launch_instance>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\traitlets\\config\\application.py’, lineno=664, function=’launch_instance’, code_context=[‘        app.start()\n’], index=0), FrameInfo(frame=<frame at 0x000002AC98403228, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel_launcher.py’, line 16, code <module>>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel_launcher.py’, lineno=16, function='<module>’, code_context=[‘    app.launch_new_instance()\n’], index=0), FrameInfo(frame=<frame at 0x000002AC985AE468, file ‘D:\\Software\\Anaconda\\lib\\runpy.py’, line 85, code _run_code>, filename=’D:\\Software\\Anaconda\\lib\\runpy.py’, lineno=85, function=’_run_code’, code_context=[‘    exec(code, run_globals)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC97CE5038, file ‘D:\\Software\\Anaconda\\lib\\runpy.py’, line 193, code _run_module_as_main>, filename=’D:\\Software\\Anaconda\\lib\\runpy.py’, lineno=193, function=’_run_module_as_main’, code_context=[‘                     “__main__”, mod_spec)\n’], index=0)]

  • getsource(): This method returns the source code of a module, class, method, or a function passes as an argument of getsource() method.

Example:

Python3






# import required modules
import inspect
  
def fun(a,b):
    # product of 
    # two numbers
    return a*b
  
# use getsource()
print(inspect.getsource(fun))

Output:

def fun(a,b):
    # product of 
    # two numbers
    return a*b
  • getmodule(): This method returns the module name of a particular object pass as an argument in this method.

Python3




# import required modules
import inspect
import collections
  
# use getmodule()
print(inspect.getmodule(collections))

Output:

<module ‘collections’ from ‘D:\\Software\\Anaconda\\lib\\collections\\__init__.py’>

  • getdoc(): The getdoc() method returns the documentation of the argument in this method as a string.

Example:

Python3




# import required modules
import inspect
from tkinter import *
  
# create object
root = Tk()
  
# use getdoc()
print(inspect.getdoc(root))

Output:

Toplevel widget of Tk which represents mostly the main window
of an application. It has an associated Tcl interpreter.

 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. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :