Search code examples
pythonpython-3.xassert

In python assert, how to print the condition when the assertion failed?


In Python, I can do:

assert result==100, "result should be 100"

but this is redundant since I have to type the condition twice.

Is there a way to tell Python to automatically show the condition when the assertion fails?


Solution

  • With pure Python, you can't reproduce the condition of the assertion automatically easily. The pytest testing framework does exactly what you want, but the implementation for this magic is everything but trivial. In short, pytest rewrites the code of your assertions to complex code to capture the information needed to generate the desired error message.