How to Catch and Print Assertion Errors in Python

5 replies · 3K views · last reply
Sunwoo Bae
Messages
60
Reaction score
4
Screenshot of a Python interactive session: a SyntaxError line, then the prompt running assert False, followed by a Traceback showing File "<input>", line 1, in <module> and AssertionError.

I would like to make output only read:

Traceback (most recent call last):
AssertionError

... without giving the File "<input>", line 1, in <module>
 
Why? The line number is there to help you debug your code. If this is to show a message to an end user then you should be using try...except, not just letting the program fail.
 
Oh its for unit testing? You should use assertRaises in your test instead of testing the crash dump output.
 
pbuk said:
Oh its for unit testing? You should use assertRaises in your test instead of testing the crash dump output.
can you tell me what assertRaises exactly do and how to use it? I have never heard about it :(
 
Hmmm, looking again I am not sure you are using a unit test framework. Is this an online tutorial? If so, stick with my first answer: catch the assertion and print its message. You can look up how to catch the failing assertion with try...except and how to get the message string from an AssertionError in a Python reference if you haven't covered them already (have you skipped some of the tutorial?).