cinit vs init

1,414 views
Skip to first unread message

ptao

unread,
Aug 13, 2010, 2:32:34 PM8/13/10
to cython-users
What is the difference between cinit and init? The documentation says
that cinit is guaranteed is guaranteed to be called once, so I've been
using that. However, when I wrote an inherited class, and used cinit
in both the base and derived classes, when I created an instance of
the inherited class, it would call the base classes constructor with
all the arguments passed into the inherited class. Because the
inherited class takes more (and different) arguments than the base
class, this caused problems.

After a little searching, I found this thread:
http://groups.google.com/group/cython-users/browse_thread/thread/dc43d862a105fafb/b59a312efdaa49a1?lnk=gst&q=inherited#b59a312efdaa49a1
which seems to suggest using init. I switched all the cinits to inits
and everything seems to work now.

However, I'm concerned about the fact that the init function might end
up being called several times. I'm doing memory allocation in the
init, and don't want to create any memory leaks. So, are inits safe to
use?

Robert Bradshaw

unread,
Aug 13, 2010, 2:51:22 PM8/13/10
to cython...@googlegroups.com

No. There are a couple of things you can do here. One option is to let
your cinit method take *args (and **kwds with a slight performance
penalty). You can also write your cinit method to take *no* arguments,
in which case it will ignore any input arguments (this is a special
case just for this purpose). Something else which I've done in the
case that the allocation is a function of the inputs is to have a flag
of whether or not the memory has been allocated, and test/set it on
entering __init__ and test it in my __dealloc__ method.

- Robert

Reply all
Reply to author
Forward
0 new messages