Tuesday, March 31, 2015

Python: tracing value of arguments in functions

If you are lazy (I am) and don't want to write print statements to trace the value of arguments, you can use this trick:

to print the argument values in case of an exception (which is most of the time the only case where you want the values to be traced...)

import inspect
def fn(x):
        frames = inspect.trace()
        argvalues = inspect.getargvalues(frames[0][0])
        print("Argvalues: ", inspect.formatargvalues(*argvalues))


('Argvalues: ', '(x=12)')

It works like magic!

I love Python.... if only it was Java, I would love it even more... let's say if Java was more Pythonic it would be a perfect world... well also if USA stopped invading and destroying countries it would not hurt...

No comments: