4

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" ?

alfredodeza
  • 5,058
  • 4
  • 35
  • 44

1 Answers1

5

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

tito
  • 12,990
  • 1
  • 55
  • 75
  • This method still work even after you've edited your question :) – tito Mar 03 '11 at 15:14
  • Absolutely right. Thanks for taking the time to edit your answer and nail it! – alfredodeza Mar 03 '11 at 15:40
  • Just tried it and worked like a charm. On a side note, `locals` returns a dict with all the args so I had to `get('a')` from locals for the `a` value. If I could give you another point I would :) – alfredodeza Mar 03 '11 at 17:49