Each Answer to this Q is separated by one/two green lines.
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?
You don’t want to break on every exception; idiomatic Python code uses exceptions heavily (EAFP) so you’d be continually breaking in unrelated code.
Instead, use pdb post-mortem:
import pdb; pdb.pm(). This uses
sys.last_traceback to inspect the stack including the locals at the throw point.
ipython supports this (http://ipython.org). from inside ipython, do
and from then on, it will automatically drop you inside the debugger whenever you get an exception.
note that you’ll (probably) quickly tire of this in general use… every time you mistype something and get a syntax error, you’ll have to exit the debugger. but it’s sometimes useful.
For python 3 (today at 3.8), this can be done with
python3 -m pdb myscript.py
From the docs:
When invoked as a script, pdb will automatically enter post-mortem
debugging if the program being debugged exits abnormally. After
post-mortem debugging (or after normal exit of the program), pdb will
restart the program. Automatic restarting preserves pdb’s state (such
as breakpoints) and in most cases is more useful than quitting the
debugger upon program’s exit.
Note that at launch, python will directly enter pdb mode, and you need to type
enter to start running the script
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()) return wrapper return decorator
@debug_on(TypeError) def buggy_function() .... raise TypeError
I know this is old and an answer has already been accepted, but I found this useful (for IPython):
start IPython with the –pdb option
ipython --pdb <whatever command>
If you want to wrap only some inner part of a function, or would need to decorate multiple functions otherwise, a context manager could be used as an alternative to the accepted answer. I am now using this simple version that catches all exceptions. I would also recommend using
from contextlib import contextmanager @contextmanager def postmortem_pudb(): try: yield except Exception as exc: pudb.post_mortem()
Use like this
with postmortem_pudb(): function_that_might_throw_some() ... another_function_that_might_throw_some() ... yet_another_function_that_might_throw_some()