If ones catches an exception outside of the function it is originally thrown, ones loses access to the local stack. As a result one cannot inspect the values of the variables that might have caused the exception.
Is there a way to automatically start break into the debugger (import pdb; pdb.set_trace()
) whenever a exception is thrown to inspect the local stack?
I found what I was looking for in an answer to What is the simplest way of using Python pdb to inspect the cause of an unhandled exception?
Wrap it with that:
def debug_on(*exceptions): if not exceptions: exceptions = (AssertionError, ) def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) except exceptions: pdb.post_mortem(sys.exc_info()[2]) return wrapper return decorator
Example:
@debug_on(TypeError) def buggy_function() .... raise TypeError