10

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}

MSeifert
  • 145,886
  • 38
  • 333
  • 352

1 Answers1

1

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
Till Hoffmann
  • 9,479
  • 6
  • 46
  • 64
  • Yeah, I have been working with default options as well, but you need to manually delete the generate source files because cython doesn't store the default variables so it knows when to recompile. But thank you very much. :) – MSeifert Aug 16 '20 at 16:52
  • You can also use `%%cython -f` which will force regeneration without having to delete the source files. – Till Hoffmann Aug 16 '20 at 20:54