Assertions and _ _debug_ _

The assert statement is used to add debugging code into a program. The general form of assert is

assert test [, data] 

where test is an expression that should evaluate to true or false. If test evaluates to false, assert raises an AssertionError exception with the optional data supplied to the assert statement. For example:

def write_data(file,data): 
    assert file, "write_data: file is None!" 
    ... 

Internally, the assert statement is translated into the following code:

if _ _debug_ _: 
   if not (test): 
      raise AssertionError, data
				

_ _debug_ _ is a built-in read-only value that’s set to 1 unless the interpreter is running in optimized mode (specified with the -O option). Although _ _debug_ _ is used by assertions, you also ...

Get Python Essential Reference, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.