Access the methods of a class

F

Fernando Rodriguez

Hi,

I have a base class with a 'sanity-check' method. This method should iterate
through all the methods and check if they are all 'thunks' (zero parameter
functions, well actually, 1 parameter: self).

How can I access the list of methods of a given object? BTW, this class will
be inherited from, so it should work with hte derived classes too.

How can I check the number of parameters of a given function object?

TIA O:)

PS Any pointers to a python reflection tutorial, would also be appreciated.
 
G

Gary Herron

Hi,

I have a base class with a 'sanity-check' method. This method should
iterate through all the methods and check if they are all 'thunks' (zero
parameter functions, well actually, 1 parameter: self).

How can I access the list of methods of a given object? BTW, this class
will be inherited from, so it should work with hte derived classes too.

How can I check the number of parameters of a given function object?

TIA O:)

PS Any pointers to a python reflection tutorial, would also be appreciated.

The inspect module should provide everything you need here.
From the manual:


inspect -- Inspect live objects

New in version 2.1.


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.


Gary Herron
 
A

Alex Martelli

Fernando said:
Hi,

I have a base class with a 'sanity-check' method. This method should
iterate through all the methods and check if they are all 'thunks' (zero
parameter functions, well actually, 1 parameter: self).

How can I access the list of methods of a given object? BTW, this class
will be inherited from, so it should work with hte derived classes too.

How can I check the number of parameters of a given function object?

TIA O:)

PS Any pointers to a python reflection tutorial, would also be
appreciated.

Check out module inspect in the standard library. It does the job
AND it's great example code for the actual lower-level mechanisms
Python offers for reflection.
.... def a(self): pass
.... def b(self): pass
.... def c(self): pass
........ def c(self): pass
.... def d(self): pass
....
import inspect as i
i.getmembers(deriv, i.ismethod)
[('a' said:
for name, method in i.getmembers(deriv, i.ismethod):
.... print name, len(i.getargspec(method)[0])
....
a 1
b 1
c 1
d 1

there -- you have the methods and the number of arguments for each.

You can also easily do more refined checks, e.g. if a method takes
*args or **kwargs the [1] and [2] items of the tuple getargspec
returns about it are going to be non-None, and in the [3] item you
have a tuple of default values so you know how many of the [0] argument
names are optional...


Alex
 
B

Bengt Richter

Hi,

I have a base class with a 'sanity-check' method. This method should iterate
through all the methods and check if they are all 'thunks' (zero parameter
functions, well actually, 1 parameter: self).

How can I access the list of methods of a given object? BTW, this class will
be inherited from, so it should work with hte derived classes too.

How can I check the number of parameters of a given function object?

TIA O:)

PS Any pointers to a python reflection tutorial, would also be appreciated.

I don't know off hand how to get the parameter count for built in methods, but:
... def m_a1(self):pass
... def m_a2(self, two):pass
... def m_a3(self, two, three=3):pass
... ... def m1(self): print 'm1'
... def m2(self): print 'm2'
... notamethod = 'not a method'
... def sanity(self):
... for name in dir(type(self)):
... if not name.startswith('_'):
... x = getattr(self, name)
... if callable(x):
... nargs = hasattr(x,'func_code') and x.func_code.co_argcount or '??'
... print '%s has %s parameter%s' % (name, nargs, 's'[:nargs!=1] )
... def twoarg(self, two): pass
... def threearg(self, two, three): pass
... append has ?? parameters
count has ?? parameters
extend has ?? parameters
index has ?? parameters
insert has ?? parameters
m1 has 1 parameter
m2 has 1 parameter
m_a1 has 1 parameter
m_a2 has 2 parameters
m_a3 has 3 parameters
pop has ?? parameters
remove has ?? parameters
reverse has ?? parameters
sanity has 1 parameter
sort has ?? parameters
threearg has 3 parameters
twoarg has 2 parameters

Regards,
Bengt Richter
 
T

Terry Reedy

Fernando Rodriguez said:
Hi,

I have a base class with a 'sanity-check' method. This method should iterate
through all the methods and check if they are all 'thunks' (zero parameter
functions, well actually, 1 parameter: self).

If you want to enforce 'sanity' rather than post-check, you might be
able to use a custom metaclass -- which gets the dictionary of
attributes as an argument. But that is an expert project not for the
faint of heart.

tjr
 
A

Alex Martelli

Terry said:
If you want to enforce 'sanity' rather than post-check, you might be
able to use a custom metaclass -- which gets the dictionary of
attributes as an argument. But that is an expert project not for the
faint of heart.

I am not a cardiologist, but I think you're emphasizing the difficulties
too much. Suppose we have a checking function that does the "atomic"
check on one function-that's-about-to-become-a-method (I showed how to
do that with inspect in a previous post) -- say a function 'dockeck'
which is called with the name and corresponding functionobject and raises
an appropriate exception if they're somehow "not right". Then packaging
the use of this function in a custom metaclass is not hard at all:

class MetaChecker(type):
def __new__(mcl, clasname, clasbases, clasdict):
for name, value in clasdict.iteritems():
if callable(value): docheck(name, value)
return type.__new__(mcl, clasname, clasbases, clasdict)

class Checked: __metaclass__ = MetaChecker


that's all -- just inherit your classes from Checked rather than from object
and all of the classes' callable attributes will be subject to whatever
checking docheck performs at class-object-creation time. (Easy to tweak if
you don't want to check all callables, again see standard module inspect
for what you can easily find out about the items in clasdict).

For anybody doing reasonably advanced things such as reflection and the
like -- and the original poster did indicate that such things were exactly
his goal -- it does not seem to me that such well-bounded and simple use
of a custom metaclass should prove forbiddingly hard or heart-threatening.


Alex
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top