trapping all method calls in a class...
clp at rebertia.com
Sun Dec 21 08:32:14 CET 2008
On Sat, Dec 20, 2008 at 11:12 PM, Piyush Anonymous
<piyush.subscription at gmail.com> wrote:
> 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
> 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:
attrs = klass.__dict__.items()
for name, val in attrs:
klass.__dict__[name] = decorate(val)
#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)"
#@decorate_meths <-- this syntax requires a later Python version
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 **
- 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...
More information about the Python-list