question with inspect module

T

Tool69

Hi,

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 ?

Thanks.
 
M

Miki

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,
 
G

Gabriel Genellina

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 ?

A more direct approach:

[name for name,value in vars(your_class).items() if
inspect.isroutine(value)]

This gets you normal, static and class methods. inspect.isfunction would
return only normal methods, and inspect.ismethoddescriptor static and
class methods.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top