Assertions

The assert statement

     def divide(a,b):
         assert b != 0, "Can't divide by zero"
         return a/b 
  • Failed assertions result in an AssertionError exception.

__debug__

  • Assertions are only enabled if the special symbol __debug__ is defined.
  • Internally, assert is expanded into this:
     if __debug__:
         if not test:
                raise AssertionError, data
  • By default, __debug__ is set 1.
  • If you run python with -O option, it is set to 0.
  • You can inspect the value of __debug__ for other purposes if you want.
<<< O'Reilly OSCON 2000, Introduction to Python, Slide 77
July 17, 2000, beazley@cs.uchicago.edu
>>>