when does `__cinit__` been called?

55 views
Skip to first unread message

Jiajun Huang

unread,
Jan 13, 2017, 5:46:00 AM1/13/17
to cython-users
hi, all:

    I'm reading <Cython, A Guide for Python Programmers>, and in the chapter 5, section `C-Level Initialization and Finalization`, it says "Cython guarantees that __cinit__ is called exactly once and that it is called before __init, __new__ or alternative Python-level constructors...". But, as far as I know

from libc.stdlib cimport malloc, free


cdef class Matrix:
    cdef:
        unsigned int nrows, ncols
        double *_matrix

    def __cinit__(self, nr, nc):
        print("[__cinit__]id of self: %s" % id(self))
        self.nrows = nr
        self.ncols = nc
        self._matrix = <double *>malloc(nr * nc * sizeof(double))
        if self._matrix == NULL:
            raise MemoryError()

    def __dealloc__(self):
        if self._matrix != NULL:
            free(self._matrix)

    # @classmethod
    # def __new__(cls, nr, nc):
        # print("id of cls: %s" % id(cls))
        # return super().__new__(cls, nr, nc)

    def __init__(self, nr, nc):
        print("[__init__]id of self: %s" % id(self))

the `self` object in `__init__` is the return value of `__new__`. and I've run it:

In [1]: import matrix

In [2]: matrix.Matrix(1, 2)
[__cinit__]id of self: 140461907621872
[__init__]id of self: 140461907621872
Out[2]: <matrix.Matrix at 0x7fbfd61bb7f0>

yes, `__cinit__` is called before `__init__`, but what about `__new__`? we can only get `self` object through `__new__`, right? so is it("Cython guarantees that __cinit__ is called exactly once and that it is called before __init, __new__ or alternative Python-level constructors...") wrong?

Robert Bradshaw

unread,
Jan 13, 2017, 12:32:04 PM1/13/17
to cython...@googlegroups.com
__new__ is not yet supported for cdef classes.
> --
>
> ---
> You received this message because you are subscribed to the Google Groups
> "cython-users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to cython-users...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Jiajun Huang

unread,
Jan 16, 2017, 2:32:22 AM1/16/17
to cython-users
thanks. :)

在 2017年1月14日星期六 UTC+8上午1:32:04,Robert Bradshaw写道:
Reply all
Reply to author
Forward
0 new messages