[Cython] Inefficient code for "is None" in boolean expressions that mix Python and C

Robert Bradshaw robertwb at math.washington.edu
Fri Feb 1 21:14:31 CET 2008


The problem is not with the if note, rather it's with the or and and.

"a or b" can returns a result of type object if either side is of  
type object. The code boils down to

res = a
if not a:
     res = b

We don't have the infrastructure to let BoolBinopNode know we want a  
bint (backwards type propagation) but we could be more clever about  
not turning the left side into a Python object until after we  
evaluate its truth value.

Fortunately __Pyx_PyBool_FromLong and __Pyx_PyObject_IsTrue are now  
macros. I wonder if the compiler is smart enough to figure out the  
meaning of them right after each other.

- Robert


On Feb 1, 2008, at 7:50 AM, Stefan Behnel wrote:

> Hi,
>
> I noticed that "is None" in a boolean expression gets unnecessarily  
> evaluated
> in Python space. This code:
>
> ----------------------
>         if stop is None and (start is None or start == 0):
> ----------------------
>
> gets compiled into this totally redundant code (plus error handling):
>
> ----------------------
> __pyx_1 = (__pyx_v_stop == Py_None);
> __pyx_2 = __Pyx_PyBool_FromLong(__pyx_1);
> __pyx_1 = __Pyx_PyObject_IsTrue(__pyx_2);
> if (__pyx_1) {
>   Py_DECREF(__pyx_2); __pyx_2 = 0;
>   __pyx_1 = (__pyx_v_start == Py_None);
>   __pyx_2 = __Pyx_PyBool_FromLong(__pyx_1);
>   __pyx_1 = __Pyx_PyObject_IsTrue(__pyx_2);
>   if (!__pyx_1) {
>     Py_DECREF(__pyx_2); __pyx_2 = 0;
>     __pyx_2 = PyObject_RichCompare(__pyx_v_start, __pyx_num_0, Py_EQ);
>   }
> }
> __pyx_1 = __Pyx_PyObject_IsTrue(__pyx_2);
> Py_DECREF(__pyx_2); __pyx_2 = 0;
> if (__pyx_1) {
> ----------------------
>
> The only thing that needs Python evaluation here is "start == 0",  
> the rest
> could run entirely in C. I don't know if it's a more general  
> problem, though,
> since all C tests should be evaluated in plain C code.
>
> Stefan
>
> _______________________________________________
> Cython-dev mailing list
> Cython-dev at codespeak.net
> http://codespeak.net/mailman/listinfo/cython-dev



More information about the Cython-dev mailing list