trapping all method calls in a class...
castironpi at gmail.com
Sun Dec 21 11:35:59 CET 2008
On Dec 21, 1:32 am, "Chris Rebert" <c... at rebertia.com> wrote:
> On Sat, Dec 20, 2008 at 11:12 PM, Piyush Anonymous
> <piyush.subscript... 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.
> > -------
> > ----
> > 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
> Follow the path of the Iguana...http://rebertia.com
Two more possibilities.
1. Use sys.settrace, and a dictionary mapping functions to integers.
The functions are given in the frame object, which is a parameter to
the settrace function.
2. __getattribute__, which either maps a function to an integer, and
returns the function; or returns a function that increments an
integer, then calls the requested function.
P.S. I did not see the original post in Google Groups.
More information about the Python-list