Search code examples
pythonassert

what is the difference between assert and a if condition embedded with a raise


i am currently learning about the assert statement in python and i cant seem to understand its main usage and what seperates it from simply raising an exception. if i wrote an if statement along with my condition and simply raised an exception if the condition is not met, how is that different from using the assert statement?

def times_ten(number):
    return number * 100
 
result = times_ten(20)
assert result == 200, 'Expected times_ten(20) to return 200, instead got ' + str(result)

to me both codes do the same thing

def times_ten(number):
    return number * 100
 
result = times_ten(20)
if  result != 200:
    raise Exception('Expected times_ten(20) to return 200, instead got ' + str(result))

Solution

  • Not much. The documentation provides the equivalent if statements to an assert statement.

    assert expression
    

    is the same as

    if __debug__:
        if not expression:
            raise AssertionError()
    

    while

    assert expression1, expression2
    

    is the same as

    if __debug__:
        if not expression1:
            raise AssertionError(expression2)
    

    As you can see, it's an AssertionError, not a generic Exception, that is raised when the condition is false, and there is a guard that can be set to False on startup (using the -O option) to prevent the assertion from being checked at all.