Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I assert from Python C code?

I'm writing a Python class in C and I want to put assertions in my debug code. assert.h suits me fine. This only gets put in debug compiles so there's no chance of an assert failure impacting a user of the Python code*.

I'm trying to divide my 'library' code (which should be separate to the code linked against Python) so I can use it from other C code. My Python methods are therefore thinnish wrappers around my pure-C code.

So I can't do this in my 'library' code:

if (black == white)
{
    PyErr_SetString(PyExc_RuntimeError, "Remap failed");
}

because this pollutes my pure-C code with Python. It's also far uglier than a simple

assert(black != white);

I believe that the Distutils compiler always sets NDEBUG, which means I can't use assert.h even in debug builds.

Mac OS and Linux.

Help!

*one argument I've heard against asserting in C code called from Python.

like image 671
Joe Avatar asked Dec 27 '10 20:12

Joe


People also ask

How do I use assert in Python?

Definition and Usage. The assert keyword is used when debugging code. The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError. You can write a message to be written if the code returns False, check the example below.

What does assert () do in C?

Assertions in C/C++ Assertions are statements used to test assumptions made by programmers. For example, we may use assertion to check if the pointer returned by malloc() is NULL or not. Following is the syntax for assertion. void assert( int expression );

Should I use assert in C?

You should only use assert to check for situations that "can't happen", e.g. that violate the invariants or postconditions of an algorithm, but probably not for input validation (certainly not in libraries). When detecting invalid input from clients, be friendly and return an error code.


1 Answers

Just use assert.h. It's a myth that distutils always defines NDEBUG; it only does so for Microsoft's msvc on Windows, and then only when invoked from a Python release build (not from a Python debug build).

To then define NDEBUG in your own release builds, pass a -D command line option to setup.py build_ext.

Edit: It seems that NDEBUG is defined by default through Python's Makefile's OPT setting. To reset this, run

OPT="-g -O3" python setup.py build
like image 155
Martin v. Löwis Avatar answered Sep 29 '22 08:09

Martin v. Löwis