How can I pass all the parameters to a decorator?
Question
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?
Solution
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 **
.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow