[Cython] [cython-users] Conditional import in pure Python mode

Stefan Behnel stefan_ml at behnel.de
Tue May 1 21:14:34 CEST 2012

Ian Bell, 01.05.2012 15:50:
> On Tue, May 1, 2012 at 9:21 PM, Stefan Behnel wrote:
>>>>> On 29 April 2012 01:33, Ian Bell wrote:
>>>>>> idiom like
>>>>>> if cython.compiled:
>>>>>>     cython.import('from libc.math cimport sin')
>>>>>> else:
>>>>>>     from math import sin
>> Actually, in this particular case, I would even accept a solution that
>> special cases the "math" module internally by automatically cimporting
>> libc.math as an override (or rather an adapted version as plain
>> "math.pxd").
>> This CEP describes a general approach:
>> http://wiki.cython.org/enhancements/overlaypythonmodules
>> It's partly outdated, so things may have become easier these days.
> That is exactly what I was looking for.  If we could implement that, it
> would solve all my problems.  It would meet all my needs - on this front at
> least.

There are two things to do here:

1) Write up a math.pxd that contains declarations equivalent to Python's
math module. Note that this may not be entirely trivial because the math
module does some error handling and type special casing under the hood.
Some of this may still be required for the C level equivalents, although
the type special casing would better be done by overriding function
signatures using this feature:


Basically, you would declare two (or more) function signatures under the
same name, but with different C names.

2) Use math.pxd as an override for the math module. I'm not sure yet how
that would best be made to work, but it shouldn't be all that complex. It
already works (mostly?) for numpy.pxd, for example, although that's done
explicitly in user code.

I think we should start with 2) to see how to get this to work in general,
before we put too much work into 1).

Could you sign up for the cython-devel mailing list please, so that we can
coordinate the work there?


More information about the cython-devel mailing list