Execute Program

Python for Programmers: Assertions

Welcome to the Assertions lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • Sometimes we want to "assert" a fact at runtime: we want to ensure that it's true, and raise an exception if it's false. We can write a function to do that for us.

  • >
    def simple_assert(value):
    if not value:
    message = str(value) + " was false"
    raise AssertionError(message)
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    simple_assert(3 == 4)
    Result:
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    simple_assert(3 == 3)
    Result:
  • (That code example returned None because the function has no explicit return value.)

  • Fortunately, we don't have to write that function because Python has an assert statement that does the same thing. assert expr raises an AssertionError if the expression expr is false.

  • (One of the next two examples raises an exception, causing an error. You can type error when a code example will cause an error.)

  • >
    x = 3
    assert x > 2
    x + 1
    Result:
    4Pass Icon
  • >
    x = 1
    assert x > 2
    x + 1
    Result:
    AssertionError: Assertion FailedPass Icon
  • In Execute Program, we've added some extra functionality to Python's assert. When assert has a false comparison with ==, like the one above, Execute Program shows us the "left" and "right" values in the exception's message. This isn't strictly necessary, but it's a nice convenience that makes debugging a bit easier.

  • >
    assert 1 + 2 == 8 - 1
    Result:
    AssertionError: Assertion Failed: 1 + 2 == 8 - 1
    
    Left:  3
    Right: 7Pass Icon
  • To reiterate: the assert statement is standard Python syntax. Execute Program only changes the AssertionError's error message. Automated testing tools written in Python often extend assert in a similar way to help with debugging.

  • Assertions are ubiquitous in unit tests and other kinds of automated tests. To test a function, we need to compare its actual output against what we expected, then raise an exception if it didn't match.

  • >
    def add(x, y):
    return x + y

    assert add(1, 2) == 3
    assert add(-4, 5) == 1
    Result:
  • Assertions can also show up in production code to enforce "invariants": things that must be true for a piece of code to work properly. For example, a function that requires a non-empty list might assert that the list is non-empty. That way, we find out immediately if we accidentally pass an empty list.

  • >
    def first(the_list):
    assert len(the_list) > 0
    return the_list[0]
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    first(["a", "b", "c"])
    Result:
    'a'Pass Icon
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    first([])
    Result:
    AssertionError: Assertion FailedPass Icon
  • (Here there are no "left" and "right" values because our assertion didn't do a comparison with ==.)

  • Python allows a custom message in the assert statement, which can provide details that might help when debugging the error.

  • >
    def first(the_list):
    assert len(the_list) > 0, "Can't get first element of empty list"
    return the_list[0]

    first([])
    Result:
    AssertionError: Can't get first element of empty listPass Icon