Python Inspect Module
The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects.
Importing the Module
import inspect
Inspecting Types
You can check the type of an object using various is functions.
import inspect
def my_func():
pass
class MyClass:
def method(self):
pass
print(inspect.ismodule(inspect)) # True
print(inspect.isclass(MyClass)) # True
print(inspect.isfunction(my_func)) # True
print(inspect.ismethod(MyClass().method)) # True
Retrieving Source Code
You can retrieve the source code of a function, class, or module.
import inspect
def hello():
print("Hello World")
print(inspect.getsource(hello))
# Output:
# def hello():
# print("Hello World")
Retrieving Documentation
You can retrieve the docstring of an object.
import inspect
def add(a, b):
"""Returns the sum of a and b."""
return a + b
print(inspect.getdoc(add))
# Output: Returns the sum of a and b.
Inspecting Signatures
The signature() function allows you to inspect the parameters of a callable.
import inspect
def func(a, b=10, *args, **kwargs):
pass
sig = inspect.signature(func)
print(sig) # Output: (a, b=10, *args, **kwargs)
for param in sig.parameters.values():
print(param.name, param.default)
Stack Inspection
inspect.stack() returns a list of frame records for the current stack.
import inspect
def a():
b()
def b():
for frame in inspect.stack():
print(frame.function)
a()
# Output (order may vary):
# b
# a
# <module>