-1

In Cython, we can add type declarations in arguments.

cdef int add(int a, int b):
  return a + b

However, the official document does not explain how to declare class objects. I want to do something like this:

cdef MY_CLASS edit_class(MY_CLASS myclassobj):
   myclassobj.edit()
   return myclassobj

More specifically, I would like to make a function that takes (pure Python) class as an argument and returns it. I know it works without specifying the type, but I am wondering if I can the same thing as I did for int a (specifying the type in argument)

Is there any way to do it? Or as said in this question, Cython does not support class?

user51966
  • 967
  • 3
  • 9
  • 21

2 Answers2

1

They're called 'extension types' so you'll have better luck looking for documentation on that. Strictly speaking, almost any python can be compiled with cython. So classes are certainly "supported" in that sense. However, if you want to take advantage of type declarations, then you need to use cdef. There are a few ways of doing it. I make my cython classes like shown below, and see a good speedup usually:

cdef class MyClass:
# first initialise 'instance' variables
cdef public str string_1
cdef public int some_number

def __cinit__(self, a_string, a_number):
    self.string_1 = a_string
    self.some_number = a_number
Neil
  • 3,020
  • 4
  • 25
  • 48
-1

Cython does support class , and it can be done using cdef.

Referring to O'Reilly ,

"The cdef class statement tells Cython to make an extension type rather than a regular Python class.

The cdef type declarations in the class body are not, despite appearances, class-level attributes. They are C-level instance attributes; this style of attribute declaration is similar to languages like C++ and Java.

All instance attributes must be declared with cdef at the class level in this way for extension types."

cdef class Particle:
    """Simple Particle extension type."""
    cdef double mass, position, velocity

So , Cython does support class , and so does CPython.

abunickabhi
  • 558
  • 2
  • 9
  • 31