Search code examples
pythonexceptionevaluate

Re-inspection of values in a Traceback


I am trying to do some elaborate re-inspection of a traceback and get actual values from the objects that are failing to return more (better?) information along with the traceback.

The case scenario is in a function that I import and execute that looks like this:

def foo():
    a = True
    b = False
    assert a == b

And gets executed like:

from foo import foo

def re_inspect():
    try:
        foo()
    except Exception, e:
         # re-inspect traceback and check `a` and `b`

When the AssertionError gets raised, if I try to evaluate the line where the exception is raised, I am (of course) unable to tell what a or b is (NameError gets raised immediately) because I am lacking the context of the code.

Do note that I do not have access to a nor b as the code above is imported and then executed. Since foo does not live in the current name space, my problem relies on getting the correct values from the foo context.

What would be the right approach to be able to tell what a and b are so that y can safely say something like: "a is True and be is False" ?


Solution

  • You can use inspect module :

    try:
        foo()
    except AssertionError, e:
        import inspect
        previous_trace = inspect.trace()[1]
        frame = previous_trace[0]
        print 'value of a, b:', inspect.getargvalues(frame).locals
    

    See http://docs.python.org/library/inspect.html#inspect.getargvalues