Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cython ipython magic with compile time environmental variables

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}

like image 833
MSeifert Avatar asked Jan 07 '17 21:01

MSeifert


1 Answers

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
like image 158
Till Hoffmann Avatar answered Oct 10 '22 04:10

Till Hoffmann