usage of assert and -O

Peter Hansen peter at engcorp.com
Tue Apr 8 20:29:22 EDT 2003


> Matthew Russell wrote:
> 
> I understand that when you invoke the interpreter with the -O flag assert 
> statments are not executed - is this 100% correct? (as i belive it to be)
> and if so, shouldn't the use of assert (if not assert itself) be depricated?

I guess you could deprecate them, but why bother?  Some people seem to
find them useful.

> I note that in unittest.py assert is not use,  we have failIf or assert_ 
> instead - thus if you avoided using assert in your own tests you can 
> saftly run all your unittests optimised....

That surely would be the idea.  Besides, assert is part of the language,
while failIf/assert_ and so on are part of the unit test framework.  There
is no particular relationship between the two.

> ..or can you...?

Yes.

> As some code in the standard library use assert,
> and since most python users' applications use library modules.....

No problem.  Asserts should not change the functionality of the 
code (except to abort it), so whether present or absent they 
shouldn't occur under normal use.  Code which causes any library
code's asserts to fire is effectively broken, since the whole point
of those asserts is to make sure those routines are never required
to handle really bad data.

> 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 ])

1. I never use -O or -OO anyway, so the issue of asserts being
removed from certain code has never come up for me.

2. I never use asserts either.

3. Unit testing should be done with a unit test framework, such
as doctest or unittest, not with asserts.  Asserts are for 
run-time protection, basically, while unit tests are run during
development.  I don't see the connection between the two.

4. Code which is dependent on the presence or absence of 
optimization done by the compiler is broken, but this should
be something checked by unit tests perhaps, not by asserts
(even if they worked when using -O).

In summary: don't bother with asserts if you're trying to do
unit testing.

-Peter




More information about the Python-list mailing list