assert (was "[Tutor] Dots-And-Boxes")

Alexandre Ratti alex@gabuzomeu.net
Sun, 02 Jun 2002 19:05:54 +0200


Hi Pijus,


At 12:00 02/06/2002 -0400, you wrote:
>From: Pijus Virketis <virketis@fas.harvard.edu>
>Date: Sun, 2 Jun 2002 11:24:20 -0400
>Subject: Re: [Tutor] Dots-And-Boxes

>Reading through Danny's code, I found a frequently used keyword "assert"

>Also, the keyword itself is not really mentioned. So, my question is this: 
>what does "assert" do, and where can I find out more about its use the way 
>Danny employs it?

Here is a short description:

"""There is now an assert statement: ``assert <condition>'' or ``assert 
<condition>, <errormessage>''. It raises AssertionError if the condition 
evaluates to false.  The default error message is empty; the source text of 
the assertion statement is printed as part of the traceback."""

Source: http://www.python.org/1.5/whatsnew.html

You can use "assert" to test a condition in a program. With "assert", you 
don't need to include "if" tests when debugging. Example:

 >>> toto = 2
 >>> assert toto > 1, "Wrong value"

Nothing happens, i.e. assertion is true.

 >>> assert toto < 1, "Wrong value"
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
AssertionError: Wrong value

Here the test failed, so you get a traceback.

I remember dimly assertion testing can be switched off for speed (with a 
command line flag, I think).


Cheers.

Alexandre