Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I force debugging python on AssertionError?

Suppose I have a python program where assert has been used to define how things should be, and I would like to capture anomalies with the read-eval-loop rather than having AssertionError be thrown.

Granted, I could have

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

but that's far more ugly in the code than a plain assert(reality==expectation).

I could have pdb.set_trace() called in an except: block at top-level, but then I'd have lost all the context of the failure, right ? (I mean, stacktrace could be recovered from the exception object, but not argument values, etc.)

Is there anything like a --magic command-line flag that could turn the python3 interpreter into what I need ?

like image 325
PypeBros Avatar asked Aug 31 '12 14:08

PypeBros


People also ask

How do I enable Python debugging?

To start the debugger from the Python interactive console, we are using run() or runeval(). To continue debugging, enter continue after the ( Pdb ) prompt and press Enter. If you want to know the options we can use in this, then after the ( Pdb ) prompt press the Tab key twice.

How do you bypass assert in Python?

Using the -O flag (capital O) disables all assert statements in a process.

Is there a debug mode for Python?

Basic debugging# If you're only interested in debugging a Python script, the simplest way is to select the down-arrow next to the run button on the editor and select Debug Python File in Terminal.

What happens when Python assert fails?

If an assertion fails, then your program should crash because a condition that was supposed to be true became false. You shouldn't change this intended behavior by catching the exception with a try … except block. A proper use of assertions is to inform developers about unrecoverable errors in a program.


2 Answers

Mainly taken from this great 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 AssertionErrors should invoke pdb.

like image 63
Constantinius Avatar answered Oct 10 '22 14:10

Constantinius


Have a look at the nose project. You can use it with the --pdb option to drop into the debugger on errors.

like image 31
apparat Avatar answered Oct 10 '22 15:10

apparat