10.7. Assertions

Assertions are diagnostic predicates which must evaluate to Boolean true; otherwise, an exception is raised to indicate that the expression is false. These work similarly to the assert macros which are part of the C language preprocessor, but in Python these are run-time constructs (as opposed to pre-compile directives).

If you are new to the concept of assertions, no problem. The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an exception is raised.

Assertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5.

10.7.1. assert Statement

The assert statement evaluates a Python expression, taking no action if the assertion succeeds (similar to a pass statement), but otherwise raises an AssertionError exception. The syntax for assert is:

							assert
							expression[, arguments]
						

Here are some examples of the use of the assert statement:

							assert 1 == 1
assert (2 + 2) == (2 * 2)
assert len(['my list', 12]) < 10
assert range(3) == [0, 1, 2]

AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback similar to the following:

>>> assert 1 == 0
Traceback (innermost last):
  File "<stdin>", line 1, in ?
AssertionError

Like the raise statement we investigated in the previous section, we can provide an exception argument to our assert command:

>>> assert 1 == 0, 'One does not equal zero silly!'
Traceback (innermost last):
  File "<stdin>", line 1, in ?
AssertionError: One does not equal zero silly!

Here is how we would use a try-except statement to catch an AssertionError exception:

							try:
							assert 1 == 0, 'One does not equal zero silly!'
except AssertionError, args:
    print '%s: %s' % (args.__class__.__name__, args)

Executing the above code from the command-line would result in the following output:

AssertionError: One does not equal zero silly!

To give you a better idea of how assert works, imagine how the assert statement may be implemented in Python if written as a function. It would probably look something like this:

							def assert(expr, args=None):
    if __debug__ and not expr:
        raise AssertionError, args

The first if statement confirms the appropriate syntax for the assert, meaning that expr should be an expression. We compare the type of expr to a real expression to verify. The second part of the function evaluates the expression and raises AssertionError, if necessary. The built-in variable __debug__ is 1 under normal circumstances, 0 when optimization is requested (command line option -O).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset