[Tutor] Another assert() question

Kent Johnson kent37 at tds.net
Sat Jul 12 22:34:00 CEST 2008

On Sat, Jul 12, 2008 at 4:01 PM, Dick Moores <rdm at rcblue.com> wrote:
> _Python in a NutShell_, p. 138 has a bit on the assert statement which I
> don't completely understand.
> It says the syntax is
> assert condition[, expression]
> I was hoping to put some sort of explanation of failure in an assert
> statement. But how to do it?
> In my code I have
> assert(len(list(set(colors_used_this_cycle))) ==
> len(colors_used_this_cycle), "A color has been used twice!")

Leave out the outermost parentheses, assert is a statement, not a function call.

In [2]: assert(False, "Asserted false")

This is "assert condition" where the condition is a tuple with two
elements, hence true so there is no output.

In [3]: assert False, "Asserted false"
<type 'exceptions.AssertionError'>        Traceback (most recent call last)

/Users/kent/<ipython console> in <module>()

<type 'exceptions.AssertionError'>: Asserted false

This is the form with an optional expression and works the way you want.


More information about the Tutor mailing list