MSe*_*ert 8 python ipython cython ipython-magic
该%%cython命令非常方便创建cython函数而无需构建和使用包.该命令有几个选项,但我找不到在那里指定编译时环境变量的方法.
我想要相当于:
from Cython.Distutils.extension import Extension
ext = Extension(...
cython_compile_time_env={'MYVAR': 10},
...)
Run Code Online (Sandbox Code Playgroud)
为%%cython命令.
我已经尝试过:
%%cython -cython_compile_time_env={'MYVAR':10}
IF MYVAR:
def func():
return 1
ELSE:
def func():
return 2
Run Code Online (Sandbox Code Playgroud)
但是这引发了一个异常:
Error compiling Cython file:
------------------------------------------------------------
...
IF MYVAR:
^
------------------------------------------------------------
...\.ipython\cython\_cython_magic_28df41ea67fec254f0be4fc74f7a6a54.pyx:2:8: Compile-time name 'MYVAR' not defined
Run Code Online (Sandbox Code Playgroud)
和
%%cython --cython_compile_time_env={'MYVAR':10}
IF MYVAR:
def func():
return 1
ELSE:
def func():
return 2
Run Code Online (Sandbox Code Playgroud)
投
UsageError:无法识别的参数: - cython_compile_time_env = {'MYVAR':10}
这是一种解决方法,而不是适当的解决方案,但它实现了所需的行为。简而言之,没有办法提供compile_time_envvia%%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
Run Code Online (Sandbox Code Playgroud)