question with inspect module

Miki miki.tebeka at gmail.com
Tue Feb 20 15:32:04 EST 2007


Hello,

> I would like to retrieve all the classes, methods and functions of a
> module.
> I've used the inspect module for this, but inside a given class
> (subclass of some other one), I wanted to retrieve only the methods
> I've written, not the inherited one. How can I do ?

class A:
    def a_method(self):
        pass

    def common_method(self):
        pass

class B(A):
    def common_method(self):
        pass

    def b_method(self):
        pass

import inspect
from os.path import abspath

lines, start_line = inspect.getsourcelines(B)
end_line = start_line + len(lines)
filename = abspath(inspect.getsourcefile(B))

for name in dir(B):
    method = getattr(B, name)
    if not callable(method):
        continue

    lnum = method.func_code.co_firstlineno
    fname = abspath(method.func_code.co_filename)

    if (lnum >= start_line) and (lnum <= end_line) and (fname ==
filename):
        print "%s is from B" % name

HTH,
--
Miki Tebeka <miki.tebeka at gmail.com>
http://pythonwise.blogspot.com




More information about the Python-list mailing list