0

I have one pure python module a.py file containing a class enhanced with cython:

@cython.cclass class Test 

How can I use this class in another pure python module 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

4
  • I suspect you have to create a .pxd definition file for both a.py and b.py and define the types there. Unfortunately, it involves duplicating information in two places, but it doesn't break the ability to use a.py and .b.py from plain Python. Commented Feb 28, 2016 at 15:39
  • I tried that, but then the cython compilation does not work anymore. For the reason that you cannot use cimport in a .pyfile to share the definition file Commented Feb 29, 2016 at 21:27
  • If you're defining the type of a function argument you could put the cimport in b.pxd file. If you're defining a type within a function I don't think you can though (in which case I don't know!) Commented Feb 29, 2016 at 22:38
  • Actually I think you can (see "magic attributes within the pxd" in the documentation) Commented Feb 29, 2016 at 22:41

1 Answer 1

1

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.

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 

You can verify that it's using the type information correctly by inspecting the generated b.c file.

For reference, the relevant documentation is http://docs.cython.org/src/tutorial/pure.html#magic-attributes-within-the-pxd

Sign up to request clarification or add additional context in comments.

1 Comment

works! I never thought of creating also a pxd file for b.py

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.