python - 在 Jupyter cdef 中运行 Cython

标签 python python-3.x cython jupyter-notebook

我正在寻找合并一些 cython 来加速我的代码。 我在 Jupyter 中运行 cython 代码时遇到问题。

单元格 1:

%%cython
cdef fuc():
    cdef int a = 0
    for i in range(10):
        a += i
        print(a)

单元格 2:

fuc()

错误:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-48-10789e9d47b8> in <module>()
----> 1 fuc()

NameError: name 'fuc' is not defined

但如果我这样做,效果很好。

%%cython
def fuc():
    cdef int a = 0
    for i in range(10):
        a += i
        print(a)

看起来 cdef 在 Jupyter 中的使用方式不同,我如何在 Jupyter notebook 中使用 cdef?

最佳答案

cdef functions can only be called from Cython, not Python .文档说

Within a Cython module, Python functions and C functions can call each other freely, but only Python functions can be called from outside the module by interpreted Python code.

(已经声明“C 函数”由 cdef 定义,“Python 函数”由 def 定义。)

改用 Cython 中的 def 函数。它仍然由 Cython 编译。您仍然可以在 def 函数中使用 cdef 类型。

关于python - 在 Jupyter cdef 中运行 Cython,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43725273/

相关文章:

python - numpy 中的条件语句。如何使用 pandas 或 numpy 将 3 个或更多个放入我的数据框中?

python - 如何在 python 中将两个列表组合成列表列表?

python - 如何计算列表末尾的出现次数

c++ - 在 C++ 中分配内存然后在 Cython 中释放它?

python - Cython 编译正常,但找不到符号 : __ZNSs4_Rep20_S_empty_rep_storageE when running on Mac OS

python - json.dumps 给我 AttributeError : 'str' object has no attribute 'get'

python-3.x - 在Python中使用OpenCV查找轮廓

python - 无法在 Python 中使用正则表达式检索所有组

python - 使用aiohttp下载tistory链接时出现403错误

python - 优化用于 numpy 方差计算的 Cython 代码