Cython ipython magic with compile time environmental variables

840 views Asked by At

The %%cython command is pretty handy to create cython functions without building and using a package. The command has several options but I couldn't find a way to specify compile time environmental variables there.

I want the equivalent of:

from Cython.Distutils.extension import Extension
ext = Extension(...
                cython_compile_time_env={'MYVAR': 10},
                ...)

for the %%cython command.

I already tried:

%%cython -cython_compile_time_env={'MYVAR':10}

IF MYVAR:
    def func():
        return 1
ELSE:
    def func():
        return 2

But that throws an Exception:

Error compiling Cython file:
------------------------------------------------------------
...

IF MYVAR:
       ^
------------------------------------------------------------

...\.ipython\cython\_cython_magic_28df41ea67fec254f0be4fc74f7a6a54.pyx:2:8: Compile-time name 'MYVAR' not defined

and

%%cython --cython_compile_time_env={'MYVAR':10}

IF MYVAR:
    def func():
        return 1
ELSE:
    def func():
        return 2

throws

UsageError: unrecognized arguments: --cython_compile_time_env={'MYVAR':10}

1

There are 1 answers

2
Till Hoffmann On BEST ANSWER

This is a little bit of a workaround rather than a proper solution, but it achieves the desired behaviour. In short, there is no way to provide a compile_time_env via the %%cython magic, but the call to cythonize picks up default compiler options that can be modified directly. For the example above, try the following.

from Cython.Compiler.Main import default_options

default_options['compile_time_env'] = {'MYVAR': 0}
# Running the magic and calling `func` yields 2

default_options['compile_time_env'] = {'MYVAR': 1}
# Running the magic and calling `func` yields 1