Skip to main content
 首页 » 编程设计

python之为 python 模块创建 .pxd 文件

2025年05月04日28pengyingh

一种使用 cython 的方法,cython 是 Python 到 C 的编译器, 不是在 Cython 中重写 Python 代码,而是编写一个与您声明变量类型的模块同名的 .pxd 文件,如 here 中所述。

有谁知道自动化或半自动化此过程的方法吗?

请您参考如下方法:

您具体要自动化什么? Cython 可以采用 python 模块并将其编译成 C,但这只能实现适度的速度提升。大部分速度提升来自于提供类型声明。这真的不是你可以自动化的事情。您必须为他们提供一种或另一种方式以获得最佳速度提升。

您可以将类型声明放在 .py 文件本身中。在 Python 解释器中运行时,类型声明无效。但是在编译时,cython 可以使用它们进行某些优化。例如。

some_module.py

def myfunction(x, y=2): 
    a = x-y 
return a + x * y 

some_module.pxd

cpdef int myfunction(int x, int y=*) 

可以改写为:

(a) 使用装饰器

@cython.locals(x=cython.int, y=cython.int, a=cython.int) 
@cython.returns(cython.int) 
def myfunction(x, y=2): 
    a = x-y 
    return a + x * y 

或者,(b) 使用注解

# cython: annotation_typing=True 
 
def myfunction(x: {'ctype': 'int'}, y: {'ctype': 'int'}=2) -> {'ctype': 'int'}: 
    a = x-y 
    return a + x * y