The inspect module in Python is useful for examining objects in your code. Since Python is an object-oriented language, this module helps inspect modules, functions and other objects to better understand their structure. It also allows for detailed analysis of function calls and tracebacks, making debugging easier. The module provides methods for verifying the type of an object and retrieving its source, with common methods categorized accordingly.
Methods to Verify the Type of Token
Inspect module offers methods to verify the type of an object, such as checking if it’s a class, module, function, or method. These tools help with introspection and understanding objects in your code.
Method
| Description
|
---|
isclass(obj)
| Returns True if obj is a class
|
---|
ismodule(obj)
| Returns True if obj is a module
|
---|
isfunction(obj)
| Returns True if obj is a function
|
---|
ismethod(obj)
| Returns True if obj is a method
|
---|
Example 1: In this example, we are checking whether a given object is a class or not. We define a simple class A and then pass it to inspect.isclass(). If the passed object is indeed a class, the method returns True.
Python
import inspect
class A:
pass
print(inspect.isclass(A))
Example 2: In this example, we are checking whether a given object is a module or not. We import the numpy module and then pass it to inspect.ismodule(). If the object passed is a module, the method returns True.
Python
import inspect
import numpy
print(inspect.ismodule(numpy))
Example 3: In this example, we check if an object is a user-defined function. The function fun returns double the input. Passing it to isfunction() returns True since it’s a valid function.
Python
import inspect
def fun(a):
return 2 * a
print(inspect.isfunction(fun))
Example 4: In this example, we use inspect.ismethod() to check if collections.Counter is a method. Since Counter is a class and not a method, ismethod() returns False.
Python
import inspect
import collections
print(inspect.ismethod(collections.Counter))
Methods to Retrieve the Source of Token
Inspect module also provides methods to retrieve the source of an object, such as inspecting class hierarchies, member functions, or function signatures. These tools help you understand the structure and source details of objects in your code.
Method
| Description
|
---|
getclasstree(classes)
| Returns a nested list of tuples showing the class hierarchy
|
---|
getmembers(obj)
| Returns all the members of an object as (name, value) pairs
|
---|
signature(callable)
| Returns the call signature of a function/method
|
---|
stack()
| Returns the call stack at the point where it’s called
|
---|
getmodule(obj)
| Returns the module in which an object was defined
|
---|
getdoc(obj)
| Returns the docstring of the object
|
---|
Example 1: In this example, we inspect the class hierarchy of C, which inherits from B and B inherits from A. We use inspect.getmro(C) to get the method resolution order and pass it to inspect.getclasstree() to get a structured inheritance tree.
Python
import inspect
class A: pass
class B(A): pass
class C(B): pass
t = inspect.getclasstree(inspect.getmro(C))
for i in t:
print(i)
Output(<class 'object'>, ())
[(<class '__main__.A'>, (<class 'object'>,)), [(<class '__main__.B'>, (<class '__main__.A'>,)), [(<class '__main__.C'>, (<class '__main__.B'>,))]]]
Example 2: In this example, we use inspect.getmembers() to fetch members of the math module and print the names and types of the first five.
Python
import inspect
import math
for n, m in inspect.getmembers(math)[:5]:
print(n, type(m))
Output__doc__ <class 'str'>
__file__ <class 'str'>
__loader__ <class '_frozen_importlib_external.ExtensionFileLoader'>
__name__ <class 'str'>
__package__ <class 'str'>
Example 3: In this example, we use inspect.signature() to get the signature of the greet function, showing its parameters and default values.
Python
import inspect
def greet(name, age=18):
return f"Hello {name}, age {age}"
s = inspect.signature(greet)
print(s)
Example 4: In this example, we use inspect.stack() to retrieve the current call stack. We then print the function names and line numbers of the top two stack frames.
Python
import inspect
def test():
stk = inspect.stack()
for f in stk[:2]: # Showing top 2 stack frames
print(f"Function: {f.function}, Line No: {f.lineno}")
test()
OutputFunction: test, Line No: 4
Function: <module>, Line No: 8
Example 5: In this example, we use inspect.getmodule() to retrieve the module that the math.sin function belongs to. We then print the name of the module using m.__name__.
Python
import inspect
import math
m = inspect.getmodule(math.sin)
print(m.__name__)
Example 6: In this example, we use inspect.getdoc() to fetch the docstring of the fun function, which describes its purpose returning the product of x and y.
Python
import inspect
def fun(x, y):
"""Returns the product of x and y."""
return x * y
print(inspect.getdoc(fun))
OutputReturns the product of x and y.
Similar Reads
Python Fire Module
Python Fire is a library to create CLI applications. It can automatically generate command line Interfaces from any object in python. It is not limited to this, it is a good tool for debugging and development purposes. With the help of Fire, you can turn existing code into CLI. In this article, we w
3 min read
Keyword Module in Python
Python provides an in-built module keyword that allows you to know about the reserved keywords of python. The keyword module allows you the functionality to know about the reserved words or keywords of Python and to check whether the value of a variable is a reserved word or not. In case you are una
2 min read
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
is keyword in Python
In programming, a keyword is a âreserved wordâ by the language that conveys special meaning to the interpreter. It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet. Python language also reserves some of the keywords that convey special meaning. In Py
2 min read
Python Modules
Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work. In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we
7 min read
PrimePy module in Python
A prime number is a natural number greater than 1 whose only factors are 1 and the number itself. 2 is the only even Prime number. We can represent any prime number with '6n+1' or '6n-1' (except 2 and 3) where n is a natural number. primePy is that library of Python which is used to compute operatio
3 min read
Indentation in Python
In Python, indentation is used to define blocks of code. It tells the Python interpreter that a group of statements belongs to a specific block. All statements with the same level of indentation are considered part of the same block. Indentation is achieved using whitespace (spaces or tabs) at the b
2 min read
Pymatrix module in python
Pymatrix is a lightweight matrix library which supports basic linear algebra operations. The elements in matrix should be numeric type to support basic algebra operations - int, float, rational, complex. Instantiating Matrix  Using Matrix constructor Matrix can be initialised using constructor of
3 min read
Pygorithm module in Python
Pygorithm module is a Python module written purely in Python and for educational purposes only. One can get the code, time complexities and much more by just importing the required algorithm. It is a good way to start learning Python programming and understanding concepts. Pygorithm module can also
2 min read
Python List of Lists
A list of lists in Python is a collection where each item is another list, allowing for multi-dimensional data storage. We access elements using two indices: one for the outer list and one for the inner list. In this article, we will explain the concept of Lists of Lists in Python, including various
3 min read