Tuesday, 25 November 2014

What is the use of “assert” in Python?

statement/function exists in mostly every other programming language out there. When you do...

assert a_condition

... you're telling the program to test that condition, and trigger an error if the condition is false. In Python, it's roughly equivalent to this:

if not condition:
    raise AssertionError()

Try it in the Python shell:

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

Assertions can include an optional message, and you can disable them when you're done debugging. See here for the relevant documentation.

No comments:

Post a Comment