usage of assert and -O

Chad Netzer cnetzer at mail.arc.nasa.gov
Tue Apr 8 20:06:38 EDT 2003


On Tue, 2003-04-08 at 16:27, Matthew Russell wrote:
> Hi all,
>  
> 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)

Yes, it is correct.

>  
> and if so, shouldn't the use of assert (if not assert itself) be
> depricated?

No.  Why?  I must assume you think the assertions should always be
evaluated, which is definitely NOT the case.  It is *trivial* to define
your own assert functions that does not get optimized away, if that is
what you want.

ie.

def always_assert( predicate ):
    if not predicate:
        raise AssertionError
 
There IS a use for an assert that can be removed during optimization.  I
often use asserts for internal consistency checking that cannot be
easily replaced with unit tests.  Once I have everything working, the
asserts (almost by definition) become redundant, and I don't necessarily
still want or need them to be evaluated in production code.

Unit tests are great at telling you WHAT functions have broken in your
code.  asserts placed judiciously in the code can help you zero in on
WHY things have broken.

I tend to define my own asserts that I don't want to go away (ie. they
become part of the API).  One such function is an argument_assert() that
I use to make sure that arguments given to a function are valid (ie.
greater than or equal to zero when appropriate, or within a predefined
range, etc.)

-- 
Bay Area Python Interest Group - http://www.baypiggies.net/

Chad Netzer
(any opinion expressed is my own and not NASA's or my employer's)







More information about the Python-list mailing list