簡體   English   中英

Cython:共享純Python模塊

[英]Cython: share pure python module

我有一個純python模塊a.py文件,其中包含一個用cython增強的類:

@cython.cclass
class Test

如何在另一個純python模塊b.py使用此類? from a import Test嘗試過from a import Test但是cython編譯器告訴我在b.py使用Test任何地方Not a type

正如我在評論中所說,您可以通過使用.pxd文件和.py文件來指定類型來做到這一點。我意識到這並不像將所有內容都放在.py文件中那樣優雅,但是我知道這是您能做的最好的事情。

a.py:

class Test:
    pass

a.pxd:

cdef class Test:
  pass

b.py:

# here I use Test in all the places I think you could want to use it:
#   as a function argument
#   as a variable in a function
#   in a class
import a

def f(x):
    return x

def g():
    t = a.Test()
    return t

class C:
    pass

b.pxd:

import cython
cimport a

cpdef f(a.Test x)

@cython.locals(t=a.Test)
cpdef g()

cdef class C:
    cdef a.Test t

您可以通過檢查生成的bc文件來驗證它是否正確使用了類型信息。

作為參考,相關文檔為http://docs.cython.org/src/tutorial/pure.html#magic-attributes-within-the-pxd

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM