Skip to content Skip to sidebar Skip to footer

Do Locally Set Cython Compiler Directives Affect One Or All Functions?

I am working on speeding up some Python/Numpy code with Cython, and am a bit unclear on the effects of 'locally' setting (as defined here in the docs) compiler directives. In my ca

Solution 1:

The documentation states that if you want to set a compiler directive globally, you need to do so with a comment at the top of the file. eg.

#!python#cython: language_level=3, boundscheck=False

Solution 2:

The manual does not say explicitly, but these directives are using decorator notation. In plain Python,

@decorator2@decorator1
def fn(args):
    body

is syntactic sugar for

def fn(args):
    bodyfn = decorator2(decorator1(fn))

So my expectation is that the directives work like that, which would mean that they apply only to the next function.

The Cython manual also says that the compiler directives can be used in with statements. What it doesn't say, unfortunately, is whether those can appear at top level:

with cython.wraparound(False), cython.boundscheck(False):

    defmyfunc1(np.ndarray[DTYPE_FLOAT_t] a):
        do things here

    defmyfunc2(np.ndarray[DTYPE_FLOAT_t] b):
        do things here

might be what you're looking for, or then again it might be a syntax error or a no-op. You're going to have to try it and see.

Post a Comment for "Do Locally Set Cython Compiler Directives Affect One Or All Functions?"