본문 바로가기
언어/ㄴPython

[python] what is assert

by 공대우냉이 2016. 1. 21.

assert 는 assert False 일때 에러를 출력하는 function이다.

Try it in the Python shell:

>>> assert True
>>> assert False
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

 

Example )

assert(2 + 2 == 5, "Houston we've got a problem")

won't work, unlike

assert 2 + 2 == 5, "Houston we've got a problem"

The reason the first one doesn't work is that bool( (False, "Houston we've got a problem") )evaluates to True.

In the statement assert(False), these are just redundant parentheses around False, which evaluate to their contents. But with assert(False,) the parentheses are now a tuple, and a non-empty tuple evaluates to True in a boolean context.

==============================================================================================================

Reference

http://stackoverflow.com/questions/5142418/what-is-the-use-of-assert-in-python