Cython

與Python相容的程式語言

Cython是结合了PythonC的语法的一种语言,可以简单的认为就是给Python加上了静态类型后的语法,用户可以维持大部分的Python语法,而不需要大幅度调整主要的程序逻辑与算法。但由于会直接编译为二进制程序,所以性能较Python会有很大提升。[5][6]

Cython
实现者Robert Bradshaw, Stefan Behnel, et al.
发行时间2007年7月28日,​16年前​(2007-07-28[1]
当前版本
  • 3.0.10 (2024年3月30日;稳定版本)[2]
编辑维基数据链接
实现语言Python
操作系统WindowsMacOSLinux
许可证Apache许可证2.0
文件扩展名.pyx, .pxd, .pxi [3]
网站cython.org 编辑维基数据链接
启发语言
C语言PythonPyrex英语Pyrex语言[4]

Cython典型的运用于编写Python扩展模块,以获取较高的执行性能。Cython将原始码转译成C或C++语法后,自动包装上函数调用界面生成.pyd(或 .so ,因操作系统而异)后缀的二进制档,即可当成普通的Python函式库。其性能一般逊于原生的C/C++函式库,但由于Cython语法的易用性可以缩短开发时间。Cython也可以用于将C/C++代码封装为Python函式库。

Cython 文件的扩展名为 .pyx。 在最基本的情况下,Cython 代码看起来与 Python 代码完全一样。 然而,虽然标准 Python 是动态类型的,但在 Cython 中,可以选择提供类型,从而提高性能,并允许在可能的情况下将循环转换为 C 循环。 [7]

语法 编辑

定义变量 编辑

可以使用关键字cdef定义变量[8]

cdef int a = 1

定义函数 编辑

可以使用关键字def、cdef、或cpdef定义函数。

cdef int f(int x):
    return x + 1

使用关键字cdef定义的函数,会被Cython编译成C语言,所以速度较快,但无法被Python使用;只有使用def或cpdef定义的函数可以在Python中使用。[9]

定义结构 编辑

cdef struct x:
  int y
  float z

使用 C 头文件 编辑

cdef extern from "stdio.h":
    int puts(const char*)

[10]

如果要使用C标准库中的函数,也可以这样写:

from libc.stdio cimport puts

使用 C++ 头文件 编辑

#distutils: language = c++
cdef extern from "<vector>" namespace "std":
    cdef cppclass vector[T]:
        vector()
        void push_back(T&)
        T& operator[](int)
        T& at(int)

[11]

或:

#distutils: language = c++
from libcpp.vector cimport vector

编译 编辑

cythonize -3 -i example.pyx

参考资料 编辑

  1. ^ Behnel, Stefan. The Cython Compiler for C-Extensions in Python. EuroPython (28 July 2007: official Cython launch). Vilnius/Lietuva. 2008 [2020-09-12]. (原始内容存档于2016-10-22). 
  2. ^ Release 3.0.10. 2024年3月30日 [2024年4月22日]. 
  3. ^ Cython支援的檔案副檔名格式 – 檔案詞典. [2020-11-23]. (原始内容存档于2022-03-31) (美国英语). 
  4. ^ Related work — Cython 3.0.0a9 documentation. cython.readthedocs.io. [2021-09-03]. (原始内容存档于2021-11-18). 
  5. ^ Cython - an overview — Cython 0.19.1 documentation. Docs.cython.org. [2013-07-21]. (原始内容存档于2013-08-11). 
  6. ^ Smith, Kurt. Cython: A Guide for Python Programmers. O'Reilly Media. 2015 [2019-05-07]. ISBN 978-1-4919-0155-7. (原始内容存档于2019-05-08). 
  7. ^ Mark Lutz. Learning Python, 5th Edition. [2021-09-17]. (原始内容存档于2021-10-08). 
  8. ^ Language Basics — Cython 3.0.0a9 documentation. cython.readthedocs.io. [2021-09-08]. (原始内容存档于2022-02-15). 
  9. ^ Language Basics — Cython 3.0.0a9 documentation. cython.readthedocs.io. [2021-09-08]. (原始内容存档于2022-02-15). 
  10. ^ Interfacing with External C Code — Cython 3.0.0a9 documentation. cython.readthedocs.io. [2021-09-09]. (原始内容存档于2022-04-25). 
  11. ^ Using C++ in Cython — Cython 3.0.0a9 documentation. cython.readthedocs.io. [2021-09-09]. (原始内容存档于2022-02-13). 

参见 编辑

外部链接 编辑