10

%%cython命令非常方便地创建 cython 函数,而无需构建和使用包。该命令有几个选项,但我找不到在那里指定编译时环境变量的方法。

我想要相当于:

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

%%cython命令。

我已经尝试过:

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

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

但这会引发异常:

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

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

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

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

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

投掷

UsageError:无法识别的参数:--cython_compile_time_env={'MYVAR':10}

4

1 回答 1

1

这是一种解决方法,而不是适当的解决方案,但它实现了所需的行为。简而言之,没有办法compile_time_env通过%%cython魔术提供一个,但是调用可以cythonize选择可以直接修改的默认编译器选项。对于上面的示例,请尝试以下操作。

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
于 2020-08-16T15:42:55.837 回答