【问题标题】:Cython: How can I create a .pxd-file for Code including an Enum?Cython:如何为包含枚举的代码创建 .pxd 文件?
【发布时间】:2020-12-20 21:57:52
【问题描述】:

我正在尝试“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。这可能是不可能的......

【问题讨论】:

    标签: cython header-files


    【解决方案1】:

    它对我有用,无需做任何特别的事情:

    testenum.pxd:

    cpdef enum AnimalType:
        Shark = 0
        Fish = 1
    

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

    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
    

    someotherfile.pyx:

    from testenum cimport AnimalType
    
    cdef class C:
        cdef AnimalType at
    

    【讨论】:

    • from testenum import AnimalType 也可以。
    • 我认为您只能在 pxd 文件中定义类型和类型声明。没想到能够设置一个枚举,然后在我想要的任何地方导入/cimport。但它的工作原理......
    • import 和 cimport 之间的区别在于,cimport Cython 在编译时知道类型。这有时很有用
    猜你喜欢
    • 1970-01-01
    • 2011-05-29
    • 2020-04-20
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多