473,320 Members | 2,189 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Access the methods of a class

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.
Jul 18 '05 #1
5 4868
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

Jul 18 '05 #2
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

Jul 18 '05 #3
On Fri, 31 Oct 2003 17:10:21 +0100, Fernando Rodriguez <fr*@easyjob.net> 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):pass
... def m_a2(self, two):pass
... def m_a3(self, two, three=3):pass
... 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
Jul 18 '05 #4

"Fernando Rodriguez" <fr*@easyjob.net> wrote in message
news:12********************************@4ax.com...
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
Jul 18 '05 #5
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
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: sedefo | last post by:
I ran into this Microsoft Patterns & Practices Enterprise Library while i was researching how i can write a database independent data access layer. In my company we already use Data Access...
11
by: Roger Leigh | last post by:
The C++ book I have to hand (Liberty and Horvath, Teach yourself C++ for Linux in 21 Days--I know there are better) states that "static member functions cannot access any non-static member...
11
by: Noah Coad [MVP .NET/C#] | last post by:
How do you make a member of a class mandatory to override with a _new_ definition? For example, when inheriting from System.Collections.CollectionBase, you are required to implement certain...
5
by: Lyle Fairfield | last post by:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/html/callnetfrcom.asp The Joy of Interoperability Sometimes a revolution in programming forces you to abandon all...
9
by: JT | last post by:
Here is the overall structure I will be referring to: End-program ProvideWorkFlow.dll Forms and methods that properly manipulate calls to methods in AccessUtils AccessUtils (a web service)...
4
by: =?Utf-8?B?c2lwcHl1Y29ubg==?= | last post by:
Hi I have a user control that is designed as below. I am creating these User Controls Dynamically in another form. They are multiple types of User Controls all with a common Interface so I can...
6
by: Adam Donahue | last post by:
As an exercise I'm attempting to write a metaclass that causes an exception to be thrown whenever a user tries to access 'attributes' (in the traditional sense) via a direct reference. Consider:...
7
by: Andy B | last post by:
I have a class I am creating for data access. I need to access controls from inside the class that are on a particular page. How do I do this? or is creating an instance of the page class and using...
2
by: fgh.vbn.rty | last post by:
Hi, I'm not sure if i'm asking the question correctly but anyway here it is. Say I have 3 classes - class A, class B, class R. 1) A and B are the building blocks and R is like a repository...
4
by: Christopher | last post by:
I am surprised this hasn't come up for me more in the past, but the situation is: I need to have an interface that is usable for all I need to have an interface that is only usable for some I...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.