Linux/Unix > Python Essential Reference, Second Edition > 5. Control Flow > Assertions and _ _debug_ _ | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137104016132042164068215009

### 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 can use it to include any sort of debugging code.

The `assert` statement should not be used for code that must be executed to make the program correct, since it won’t be executed if Python is run in optimized mode. In particular, it’s an error to use `assert` to check user input. Instead, `assert` statements are used to check things that should always be true; if one is violated, it represents a bug in the program, not an error by the user.

For example, if the function `write_data()` shown here were intended for use by an end user, the `assert` statement should be replaced by a conventional `if` statement and the desired error handling.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.