简体   繁体   English

Cython:共享纯Python模块

[英]Cython: share pure python module

I have one pure python module a.py file containing a class enhanced with cython: 我有一个纯python模块a.py文件,其中包含一个用cython增强的类:

@cython.cclass
class Test

How can I use this class in another pure python module b.py ? 如何在另一个纯python模块b.py使用此类? I tried from a import Test but then the cython compiler tells me Not a type wherever I use Test in b.py from a import Test尝试过from a import Test但是cython编译器告诉我在b.py使用Test任何地方Not a type

As I said in the comments, you can do it by using .pxd files in addition to the .py files to specify the types in. I realise this isn't as elegant as putting everything in the .py files, but as far as I know it's the best you can do. 正如我在评论中所说,您可以通过使用.pxd文件和.py文件来指定类型来做到这一点。我意识到这并不像将所有内容都放在.py文件中那样优雅,但是我知道这是您能做的最好的事情。

a.py: a.py:

class Test:
    pass

a.pxd: a.pxd:

cdef class Test:
  pass

b.py: 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: 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

You can verify that it's using the type information correctly by inspecting the generated bc file. 您可以通过检查生成的bc文件来验证它是否正确使用了类型信息。

For reference, the relevant documentation is http://docs.cython.org/src/tutorial/pure.html#magic-attributes-within-the-pxd 作为参考,相关文档为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