When to use assert
Jan. 15th, 2014 08:06 pmPython's
Many people use assertions as a quick and easy way to raise an exception if an argument is given the wrong value. But this is wrong, badly wrong, for two reasons. ( Read more... )
assert
statement is a very useful feature that unfortunately often gets misused. assert
takes an expression and an optional error message, evaluates the expression, and if it gives a true value, does nothing. If the expression evaluates to a false value, it raises an AssertionError
exception with optional error message. For example:py> x = 23 py> assert x > 0, "x is zero or negative" py> assert x%2 == 0, "x is an odd number" Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError: x is an odd number
Many people use assertions as a quick and easy way to raise an exception if an argument is given the wrong value. But this is wrong, badly wrong, for two reasons. ( Read more... )