Skip to Content
Python: Essential Reference, Third Edition
book

Python: Essential Reference, Third Edition

by David Beazley
February 2006
Intermediate to advanced content levelIntermediate to advanced
648 pages
14h 53m
English
Sams
Content preview from Python: Essential Reference, Third Edition

Assertions and __debug__

The assert statement can introduce 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!"
    ...

Assertions are not checked when Python runs in optimized mode (specified with the –O option).

In addition to assert, Python provides the built-in read-only variable __debug__, which is set to 1 unless the interpreter is running in optimized mode (specified with the -O option). Programs can examine this variable as needed—possibly ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python: Essential Reference

Python: Essential Reference

David M. Beazley

Publisher Resources

ISBN: 0672328623Purchase book