首页 > 解决方案 > Cython:如何为包含枚举的代码创建 .pxd 文件?

问题描述

我正在尝试“cythonize”以下示例代码,其中包括 Enum 类的实例:

from enum import Enum
class AnimalType(Enum):
    Shark = 0
    Fish = 1

class Animal:
    def __init__(self, animal_type: AnimalType, weight: float):
        self.animal_type = animal_type
        self.weight = weight

创建带有类型声明的 .pyx 文件很容易:

cpdef enum AnimalType:
    Shark = 0
    Fish = 1

cdef class Animal:
    cdef double weight
    cdef AnimalType animal_type

    def __init__(self, animal_type: AnimalType, weight: float):
        self.animal_type = animal_type
        self.weight = weight

但是,我无法将 .pyx 文件拆分为 .pyx 和 .pxd(标头)文件。您能帮我为我的示例定义一个 .pxd 文件吗?

编辑:我已阅读https://groups.google.com/g/cython-users/c/ZoLsLHwnUY4。可能无法做到这一点......

标签: cythonheader-files

解决方案


它适用于我而无需做任何特别的事情:

睾丸.pxd:

cpdef enum AnimalType:
    Shark = 0
    Fish = 1

(如果你也想分享 Cython 的定义,你也可以把cdef部分放在那里)。Animal

testenum.pyx:

# no need to cimport testenum - this happens implicitly

cdef class Animal:
    cdef double weight   # omit this if you put it in the pxd file
    cdef AnimalType animal_type   # omit this if you put it in the pxd file

    def __init__(self, animal_type: AnimalType, weight: float):
        self.animal_type = animal_type
        self.weight = weight

其他文件.pyx:

from testenum cimport AnimalType

cdef class C:
    cdef AnimalType at

推荐阅读