Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Access the methods of a class

Reply
Thread Tools

Access the methods of a class

 
 
Fernando Rodriguez
Guest
Posts: n/a
 
      10-31-2003
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.
 
Reply With Quote
 
 
 
 
Gary Herron
Guest
Posts: n/a
 
      10-31-2003
On Friday 31 October 2003 08:10 am, Fernando Rodriguez wrote:
> 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



 
Reply With Quote
 
 
 
 
Alex Martelli
Guest
Posts: n/a
 
      10-31-2003
Fernando Rodriguez wrote:

> 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.

>>> class base(object):

.... def a(self): pass
.... def b(self): pass
.... def c(self): pass
....
>>> class deriv(base):

.... def c(self): pass
.... def d(self): pass
....
>>> import inspect as i
>>> i.getmembers(deriv, i.ismethod)

[('a', <unbound method deriv.a>), ('b', <unbound method deriv.b>), ('c',
<unbound method deriv.c>), ('d', <unbound method deriv.d>)]
>>> 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

 
Reply With Quote
 
Bengt Richter
Guest
Posts: n/a
 
      10-31-2003
On Fri, 31 Oct 2003 17:10:21 +0100, Fernando Rodriguez <(E-Mail Removed)> wrote:

>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:

>>> class A(object):

... def m_a1(self)ass
... def m_a2(self, two)ass
... def m_a3(self, two, three=3)ass
...
>>> class Foo(A, list):

... 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
...
>>> foo = Foo()
>>> foo.sanity()

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
 
Reply With Quote
 
Terry Reedy
Guest
Posts: n/a
 
      11-01-2003

"Fernando Rodriguez" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
> 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


 
Reply With Quote
 
Alex Martelli
Guest
Posts: n/a
 
      11-01-2003
Terry Reedy wrote:

>> 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.


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


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
list of 'magic methods' or builtin class methods... want to excludethose from dir output DG Python 3 07-22-2009 07:24 PM
calling class methods from class methods, help? Oltmans Python 6 03-11-2009 07:59 PM
Is there a way to find the class methods of a class, just like'methods' finds the instance methods? Kenneth McDonald Ruby 5 09-26-2008 03:09 PM
Nested Class, Member Class, Inner Class, Local Class, Anonymous Class E11 Java 1 10-12-2005 03:34 PM
difference between class methods and instance methods John M. Gabriele Python 18 02-18-2005 05:17 PM



Advertisments