Skip to contentSkip to conversation

Cython and conditional compilation

DISCUSSION Florian Weimer 1 participant 1 message Feb 9, 2023

lore
Share & tools
lore
#0 lore raw

Cython/Includes/cpython/version.pxd contains this recommendation:

# Python version constants
#
# It's better to evaluate these at runtime (i.e. C compile time) using #
# if PY_MAJOR_VERSION >= 3:
# do_stuff_in_Py3_0_and_later()
# if PY_VERSION_HEX >= 0x02070000:
# do_stuff_in_Py2_7_and_later()
#

# than using the IF/DEF statements, which are evaluated at Cython
# compile time.  This will keep your C code portable.

I have seen one case, in an older version of breezy, where this only works because the compiler accepts calls to undeclared functions (implicit function declarations) and optimizes out the branches not taken:

cdef object _split_first_line_unicode(Py_UNICODE *line, int len,
Py_UNICODE *value, Py_ssize_t *value_len):
cdef int i
for i from 0 <= i < len:
if line[i] == c':':
if line[i+1] != c' ':
raise ValueError("invalid tag in line %r" %
PyUnicode_FromUnicode(line, len))
memcpy(value, &line[i+2], (len-i-2) * sizeof(Py_UNICODE)) value_len[0] = len-i-2
if PY_MAJOR_VERSION >= 3:
return PyUnicode_FromUnicode(line, i)
return PyUnicode_EncodeASCII(line, i, "strict")
raise ValueError("tag/value separator not found in line %r" %
PyUnicode_FromUnicode(line, len))

The PyUnicode_EncodeASCII still ends up in the generated C code, but it's no longer part of the Python 3 API, hence the implicit function declaration.

It's since been fixed in breezy, but maybe it makes sense to revise the recommendation in version.pxd?

Thanks,
Florian