Python introspection with the inspect module

Here are some fun and potentially useful tricks you can do using the inspect module.

Get a list of currently imported modules:

import inspect

myglobals = dict()
modules = [value
           for key, value in myglobals.items()
           if inspect.ismodule(value)]

Get a list of classes in a module (by Marc 'BlackJack' Rintsch):

import module
from inspect import getmembers, isclass

classes = getmembers(module, isclass)

Get all "callables" (e.g. methods) in an object:

import inspect

class Spam:
    plumage = "lovely"

    def __init__(self):
        self.variety = "Norwegian Blue"
        self.dead = lambda : not self.alive()

    def alive(self):
        return False

print "For Spam class"
for name, value in inspect.getmembers(Spam, callable):
    print "    Callable:", name

print "For Spam instance"
for name, value in inspect.getmembers(Spam(), callable):
    print "    Callable:", name


For Spam class
    Callable: __init__
    Callable: alive
For Spam instance
    Callable: __init__
    Callable: alive
    Callable: dead

Get the file name and starting line number of an object:

import inspect

def get_file_and_line_num(obj):
    filename = inspect.getabsfile(obj)
    source, line_num = inspect.findsource(obj)
    return filename, line_num

Leave a Reply




You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>