I love assert

Terry Reedy tjreedy at udel.edu
Tue Nov 11 17:34:27 EST 2014


On 11/11/2014 2:40 PM, Peter Cacioppi wrote:
> I get the impression that most Pythonistas aren't as habituated with
> assert statements as I am. Is that just a misimpression on my part?
> If not, is there a good reason to assert less with Python than other
> languages?

We love 'assert' so much that we have 20-30 'assertXYZ' variations in 
unittest.  The statement 'assert expression' is almost equivalent to

if not expression: raise AssertionError('expression')

We have perhaps 100 mostly more specialized exceptions builtin and in 
the stdlib.  There is nearly always a better, more specific exception 
and error message.

> As far as I can tell, Python supports assert perfectly well. When run
> with the optimization flagging, the asserts are truly removed.

Separating tests from main code removes test asserts from the main code. 
  Removal by -0 relegates bare assert to specialized usage.

> I think one needs to take care with some basic assert coding - it's
> not a substitute for unit tests, it doesn't absolve you of normal
> exception responsibilities, and, most of all, it should be used for
> passive inspection and not action. But given these guidelines, I
> still find it very useful as "active comments".

How much usage depends considerably on the programmer.

-- 
Terry Jan Reedy




More information about the Python-list mailing list