Take the 2-minute tour ×

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?

share|improve this question
What's the point of xargs = args? you can just pass args to the % operator directly. –  Algorias Mar 9 '09 at 18:10
add comment

1 Answer

up vote 6 down vote accepted

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 **.

share|improve this answer
Both argument lists should read (*args, **kwargs) to handle functions/methods with keyword arguments also. –  Ber Mar 9 '09 at 11:39
add comment

Your Answer


