Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle AssertionError in Python and find out which line or statement it occurred on?

Tags:

python

assert

I want to handle AssertionErrors both to hide unnecessary parts of the stack trace from the user and to print a message as to why the error occurred and what the user should do about it.

Is there any way to find out on which line or statement the assert failed within the except block?

try:
    assert True
    assert 7 == 7
    assert 1 == 2
    # many more statements like this
except AssertionError:
    print 'Houston, we have a problem.'
    print
    print 'An error occurred on line ???? in statement ???'
    exit(1)

I don't want to have to add this to every assert statement:

assert 7 == 7, "7 == 7"

because it repeats information.

like image 484
devtk Avatar asked Jul 20 '12 21:07

devtk


People also ask

How does Python handle AssertionError?

Use the Logging Module With Try-Except Blocks to Handle the Assertion Error in Python. The logging module in Python helps you keep track of the execution and errors of an application. This module keeps track of the events that take place during any operation.

How do you handle assert failed exception in Python?

If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback.

How do I raise AssertionError in Python?

Python - Assert Statement In Python, the assert statement is used to continue the execute if the given condition evaluates to True. If the assert condition evaluates to False, then it raises the AssertionError exception with the specified error message.

What is an assertion statement in Python?

What Are Assertions? In Python, assertions are statements that you can use to set sanity checks during the development process. Assertions allow you to test the correctness of your code by checking if some specific conditions remain true, which can come in handy while you're debugging code.


2 Answers

Use the traceback module:

import sys
import traceback

try:
    assert True
    assert 7 == 7
    assert 1 == 2
    # many more statements like this
except AssertionError:
    _, _, tb = sys.exc_info()
    traceback.print_tb(tb) # Fixed format
    tb_info = traceback.extract_tb(tb)
    filename, line, func, text = tb_info[-1]

    print('An error occurred on line {} in statement {}'.format(line, text))
    exit(1)
like image 50
phihag Avatar answered Oct 10 '22 15:10

phihag


The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

Which gives the following output that includes the offending statement and line number:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)
like image 40
notpeter Avatar answered Oct 10 '22 15:10

notpeter