Python inspect

·

1 min read

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. For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback.

import inspect

class Test:
    def __init__(self):
        pass
    def add(self, a, b):
        return a + b
ins = inspect.getmembers(Test)
for i in ins:
    print(i)

Get something like

('__module__', '__main__')
('__ne__', <slot wrapper '__ne__' of 'object' objects>)
('__new__', <built-in method __new__ of type object at 0x100f20590>)
('__reduce__', <method '__reduce__' of 'object' objects>)
('__reduce_ex__', <method '__reduce_ex__' of 'object' objects>)
('__repr__', <slot wrapper '__repr__' of 'object' objects>)
('__setattr__', <slot wrapper '__setattr__' of 'object' objects>)
('__sizeof__', <method '__sizeof__' of 'object' objects>)
('__str__', <slot wrapper '__str__' of 'object' objects>)
('__subclasshook__', <built-in method __subclasshook__ of type object at 0x14fe67490>)
('__weakref__', <attribute '__weakref__' of 'Test' objects>)
('add', <function Test.add at 0x1014577e0>)

Get the source code of a function

import inspect

def add(a, b):
    return a+b

source = inspect.getsource(add)
print(source)