Python’s Assert Syntax
It’s always a good idea to study up on how a language feature is actually implemented in Python before you start using it. So let’s take a quick look at the syntax for the assert statement, according to the Python docs:
assert_stmt :: = "assert" expression1 ["," expression2]
In this case, expression1 is the condition we test, and the optional expression2 is an error message that’s displayed if the assertion fails.At execution time, the Python interpreter transforms each assert statement into roughly the following sequence of statements:
if __debug__:
if not expression1:
raise AssertionError(expression2)
Two interesting things about this code snippet:
Before the assert condition is checked, there’s an additional check for the debug global variable. It’s a built-in boolean flag that’s true under normal circumstances and false if optimizations are requested.We’ll talk some more about that later in the “common pitfalls” section.
Also, you can use expression2 to pass an optional error message that will be displayed with the AssertionError in the traceback. This can simplify debugging even further. For example, I’ve seen code like this:
>>> if cond == 'x':
... do_x()
... elif cond == 'y':
... do_y()
... else:
... assert False, (
... 'This should never happen, but it does '
... 'occasionally. We are currently trying to '
... 'figure out why. Email dbader if you '
... 'encounter this in the wild. Thanks!')
Is this ugly?Well, yes. But it’s definitely a valid and helpful technique if you’re faced with a Heisenbug in one of your applications.
Notification:
Wikipedia:Heisenbug