views:

153

answers:

1

I tried to trace the execution of some methods using a decorator. Here is the decorator code:



def trace(func):
    def ofunc(*args):
     func_name = func.__name__  
     xargs = args  
     print "entering %s with args %s" % (func_name,xargs)
     ret_val = func(args)
     print "return value %s" % ret_val
     print "exiting %s" % (func_name)
    return ofunc 

The thing is, if I try to apply this decorator to methods, the self parameter doesn't get sent. Can you tell me why, and how can I fix that?

+7  A: 

This line is incorrect:

ret_val = func(args)

You're forgetting to expand the argument list when you're passing it on. It should be:

ret_val = func(*args)

Sample output with this modification in place:

>>> class Test2:
...     @trace
...     def test3(self, a, b):
...        pass
... 
>>> t = Test2()
>>> t.test3(1,2)
entering test3 with args (<__main__.Test2 instance at 0x7ff2b42c>, 1, 2)
return value None
exiting test3
>>>

If you ever expand your decorator to also take keyword arguments, you'd also need to expand those appropriately when passing them on, using **.

insin
Both argument lists should read `(*args, **kwargs)` to handle functions/methods with keyword arguments also.
Ber