3

In Cython, a class, or a extension type is a Python class, which means it can be initialized by Python. On the other hand, the parameters of its __init__ or __cinit__ have to be Python Object.

Is it possible to write a class in Cython, which can only be initilized by cdef functions, and thus can be initilized by C types and C++ objects?

I want to this because it would be easier to translate my existing Python codes to Cython code than C/C++ code.

DavidW
  • 29,336
  • 6
  • 55
  • 86
iuradz
  • 1,128
  • 1
  • 12
  • 25
  • 1
    I found it is possible to write c++ class by cdef cppclass. However, a lot of c++ features such as destructor function, overloading constructor are not supported. Maybe they will be supported in future versions? – iuradz Mar 28 '16 at 10:00

1 Answers1

1

You can quite easily create a class that can't (easily) be initialised from Python, but can only be created from a cdef factory function

cdef class ExampleNoPyInit:
    cdef int value

    def __init__(self):
        raise RuntimeError("Cannot be initialise from python")

cdef ExampleNoPyInit_factory(int v):
    cdef ExampleNoPyInit a

    # bypass __init__
    a = ExampleNoPyInit.__new__(ExampleNoPyInit) 
    a.value = v
    return a

inst = ExampleNoPyInit_factory(5)

(I suspect the really committed could use the same method of initialising it in Python if they wanted. There are other ways to prevent initialisation if you want to be more thorough - for example you could use a cdef global variable in your Cython module as a flag, which would not be accessed from Python).

This class still has the Python reference counting mechanism built-in so is still a "Python class". If you want to avoid that then you could use a cdef struct, (although that can't have member functions).

Stephane Rolland
  • 38,876
  • 35
  • 121
  • 169
DavidW
  • 29,336
  • 6
  • 55
  • 86
  • Are there any performance limitations for using a pure cython class for storing data vs using a struct? – ajl123 Mar 14 '22 at 23:19
  • Accessing the stored data in a Cython class should be as quick as in a struct. Creating a Cython class will be a little slower because it involves heap allocation. – DavidW Mar 15 '22 at 06:44