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:
http://stackoverflow.com/questions/6061744/how-to-get-value-of-arguments-in-functions-at-stack

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):
    try:
        print(1/0)
    except:
        frames = inspect.trace()
        argvalues = inspect.getargvalues(frames[0][0])
        print("Argvalues: ", inspect.formatargvalues(*argvalues))
        raise

fn(12)


('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: