usage of assert and -O

Steven Taschuk staschuk at telusplanet.net
Tue Apr 8 21:47:38 EDT 2003


Quoth Matthew Russell:
  [...]
> I would be interested to know what others think about usage of
> assert in context with optimised python code, in particular in
> releation to unittesting, as this is where i think it would be
> useful - if not critical to have one way of doing it (i.e not
> useing assert or -O [ one or the other ])

The assert statement is not well-suited for testing, precisely
because, as you point out, it gets optimized away.  For testing
you want a testing framework such as unittest or doctest.

They are also not useful for checking input or arguments, again
because they get optimized away.  For this you want an explicit
"if spam: raise eggs".

As Netzer pointed out, assert *is* useful for internal consistency
checks; such checks are handy when the code is under development,
to help pin down problems as they arise.  When the code ships,
presumably these checks are no longer necessary (because the code
works) and can be freely optimized into oblivion.

Asserts can also be somewhat useful as documentation; one might,
for example, assert an invariant of a data structure or a loop.
Here it is desirable that these assertions get optimized away
except when debugging.  (A comment can serve this purpose almost
as well; but assertions have the advantage of being automatically
checked for correctness.)

-- 
Steven Taschuk                                7\ 7'Z {&~         .
staschuk at telusplanet.net                        Y r          --/hG-
                                            (__/ )_             1^1`





More information about the Python-list mailing list