12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Running a raise this way reraises the exception, and propagates it to a higher handler,or the default handler at the top, which stops the program with a standard errormessage.The assert StatementAs a somewhat special case, <strong>Python</strong> includes the assert statement. It is mostlysyntactic shorthand for a common raise usage pattern, and can be thought of as aconditional raise statement. A statement of the form:assert , works like the following code:if _ _debug_ _:if not :raise AssertionError, # The part is optionalIn other words, if the test evaluates to false, <strong>Python</strong> raises an exception: the data item(if it’s provided) as the exception’s extra data. Like all exceptions, the AssertionErrorexception raised will kill your program if it’s not caught with a try.As an added feature, assert statements may be removed from a compiled program’sbyte code if the -O <strong>Python</strong> command-line flag is used, thereby optimizing the program.AssertionError is a built-in exception, and the _ _debug_ _ flag is a built-inname that is automatically set to 1 (true) unless the -O flag is used.Example: Trapping Constraints (but Not Errors)Assertions are typically used to verify program conditions during development.When displayed, their error message text automatically includes source code lineinformation, and the value listed in the assert statement. Consider the file asserter.py:def f(x):assert x < 0, 'x must be negative'return x ** 2% python>>> import asserter>>> asserter.f(1)Traceback (most recent call last):File "", line 1, in ?File "asserter.py", line 2, in fassert x < 0, 'x must be negative'AssertionError: x must be negativeIt’s important to keep in mind that assert is mostly intended for trapping userdefinedconstraints, not for catching genuine programming errors. Because <strong>Python</strong>The assert Statement | 595

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!