trapping all method calls in a class...
Chris Rebert
clp at rebertia.com
Sun Dec 21 02:32:14 EST 2008
On Sat, Dec 20, 2008 at 11:12 PM, Piyush Anonymous
<piyush.subscription at gmail.com> wrote:
> hi,
> i need to trap all method calls in a class in order to update a counter
> which is increased whenever a method is called and decreased whenever method
> returns. in order to that i am trying to write a decorator for all the
> methods.
>
> see the code here with error.
> -------
> http://codepad.org/2w7JVvDB
> ----
> any suggestions? any other better way of doing it?
I call unnecessary use of metaclasses! Here's my (untested) attempt at
a simpler class decorator approach:
def decorate_meths(klass):
attrs = klass.__dict__.items()
for name, val in attrs:
if callable(val):
klass.__dict__[name] = decorate(val)
def decorate(method):
#should be called for every method call in the class
def decorated(self, *args, **kwds):
print "2 Inside __call__()"
returnval = method(self, *args,**kwds)
print "3 After self.f(*args)"
return returnval
return decorated
#@decorate_meths <-- this syntax requires a later Python version
class Person(object):
def testprint(self,val):
print "blah blah"
Person = decorate_meths(Person)
#rest of code after the class definition would be the same
Sidenotes about your code:
- `args` and `kwds` are the conventional names for the * and **
special arguments
- the `methodname` variable was actually getting method objects, not
strings, as its values; this was probably part of the bug in your
program
Cheers,
Chris
--
Follow the path of the Iguana...
http://rebertia.com
More information about the Python-list
mailing list