2

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))
gix
  • 37
  • 4
  • 1
    A failed `assert` will raise an `AssertionError`, which may or may not be the closest semantic meaning you want to convey to the caller. See the list of [concrete exceptions](https://docs.python.org/3/library/exceptions.html#concrete-exceptions). Maybe it is more meaningful to raise a `ValueError` or `IndexError`, etc. – Cory Kramer Jan 30 '23 at 14:55
  • `assert` statements are also only effective when `__debug__` is set to true, which means you can disable them at runtime without modifying the code. See https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement. – chepner Jan 30 '23 at 14:58

1 Answers1

3

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.

chepner
  • 497,756
  • 71
  • 530
  • 681