trapping all method calls in a class...
MrJean1 at gmail.com
Sun Dec 21 21:43:47 CET 2008
The decorate_meths() function as given fails:
TypeError: 'dictproxy' object does not support item assignment
But this version avoids that error (on Python 2.2 thru 2.6):
for nam, val in klass.__dict__.items():
setattr(klass, nam, decorate(val))
return klass # ?
On Dec 20, 11:32 pm, "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
More information about the Python-list