[Cython] Bug: bad C code generated for (some) "... and ... or ..." expressions

Stefan Behnel stefan_ml at behnel.de
Fri Jun 8 08:50:47 CEST 2012


thanks for the report.

Dieter Maurer, 07.06.2012 10:44:
> "cython 0.13" generates bad C code for the attached "pyx" file.

Could you try the latest release? I would at least expect an error instead
of actually generating code.

> "cython" itself recognizes that it did something wrong and emits "<error>;"
> to the generated file:
> ...
> static  __pyx_t_12cybug_and_or_pointer __pyx_f_12cybug_and_or_bug(PyObject *__pyx_v_o) {
>   __pyx_t_12cybug_and_or_pointer __pyx_r;
>   int __pyx_t_1;
>   __pyx_t_12cybug_and_or_pointer __pyx_t_2;
>   <error>;
>   <error>;
> ...

This is generated from this Cython code:

> cdef pointer bug(o):
>   return o is not None and to_pointer(o) or NULL

The right way to implement this is:

   return to_pointer(o) if o is not None else NULL

> The error probably happens because it is difficult for "cython" to
> determine the type for "and" and "or" expressions (if the operand types
> differ). In an "cond and t or f" expression, however, the result type
> is "type(t)" if "type(t) == type(f)", independent of "type(cond)".

Independent of the condition, yes. However, the types of the two expression
results differ here, and the fact that you named your initial condition
"cond" just hides the fact that it is not different from the other two
parts (t and f) of the expression. The Python semantics of this kind of
evaluation is more complex than you might think.

> It might not be worse to special case this type of expressions.


> It would however be more friendly to output an instructive
> error message instead of generating bad C code.



More information about the cython-devel mailing list