using C's "assert" macro in extension code

Skip Montanaro skip at pobox.com
Wed Mar 26 13:48:53 EST 2003


    Maciej> I tend to litter my experimental code with a healthy dose of
    Maciej> "assert" statements, and writing Python extensions is no
    Maciej> exception.  I've recently noticed that my asserts are not being
    Maciej> executed, which led me to realize that the Makefile created by
    Maciej> "make -f Makefile.pre.in boot" always uses "-DNDEBUG", which
    Maciej> disables the assert macro.  Does this mean that using C's
    Maciej> asserts in extension code is frowned upon?  

No, it just means that to get asserts in your code you need to do a debug build.

    Maciej> I know it's not as clean as properly handling the problem and
    Maciej> letting the Python interpreter know about it, but sometimes when
    Maciej> writing one-off code you don't really want/need to bother being
    Maciej> robust.  If asserts are undesirable for some reason, what is the
    Maciej> accepted way of doing the equivalent?

Raise an exception and let the script catch it.

Python's philosophy is that the interpreter should never "just quit".  The
programmer is the person who writes the Python script.  S/He should be the
one to decide if the program should quit.  To that end, if you expect
potential problems at runtime, you should always raise an exception, even
from an extension module.

Skip






More information about the Python-list mailing list