Can I force debug python on an AssertionError?

Suppose I have a python program where assert is used to determine how it should be, and I would like to capture the anomalies with a read-eval loop rather than throwing an AssertionError .

Of course I could

 if (reality!=expectation): print("assertion failed"); import pdb; pdb.set_trace(); 

but this is much more ugly in code than a simple assert(reality==expectation) .

I could have pdb.set_trace() called in the except: block at the top level, but then I would lose the entire failure context, right? (I mean, stacktrace can be restored from an exception object, but not the value of the arguments, etc.)

Is there something like the --magic command line --magic that can turn the python3 interpreter into what I need?

+7
source share
2 answers

Mostly taken from this wonderful snippet :

 import sys def info(type, value, tb): if hasattr(sys, 'ps1') or not sys.stderr.isatty() or type != AssertionError: # we are in interactive mode or we don't have a tty-like # device, so we call the default hook sys.__excepthook__(type, value, tb) else: import traceback, pdb # we are NOT in interactive mode, print the exception... traceback.print_exception(type, value, tb) print # ...then start the debugger in post-mortem mode. pdb.pm() sys.excepthook = info 

When you initialize your code with this, all AssertionError should raise pdb.

+11
source

Look at the nose project. You can use it with the - pdb option to throw errors into the debugger.

+4
source

All Articles