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
Nonebecause the function has no explicit return value.)Fortunately, we don't have to write that function because Python has an
assertstatement that does the same thing.assert exprraises anAssertionErrorif the expressionexpris false.(One of the next two examples raises an exception, causing an error. You can type
errorwhen a code example will cause an error.)>
x = 3assert x > 2x + 1Result:
4
>
x = 1assert x > 2x + 1Result:
AssertionError: Assertion Failed
In Execute Program, we've added some extra functionality to Python's
assert. Whenasserthas 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 - 1Result:
AssertionError: Assertion Failed: 1 + 2 == 8 - 1 Left: 3 Right: 7
To reiterate: the
assertstatement is standard Python syntax. Execute Program only changes theAssertionError's error message. Automated testing tools written in Python often extendassertin 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 + yassert add(1, 2) == 3assert add(-4, 5) == 1Result:
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) > 0return the_list[0]- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
first(["a", "b", "c"])Result:
'a'
- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
first([])Result:
AssertionError: Assertion Failed
(Here there are no "left" and "right" values because our assertion didn't do a comparison with
==.)Python allows a custom message in the
assertstatement, 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 list