[Cython] Hooking tp_clear()

Jeroen Demeyer J.Demeyer at UGent.be
Thu Sep 6 16:54:52 EDT 2018


Hello,

Cython's __dealloc__ special method is meant to deal with cleaning up 
instances of cdef classes. However, this hooks tp_dealloc() and does not 
have meaningful access to Python attributes, since those might have been 
cleared by tp_clear().

I have a concrete use case where I want something like __dealloc__ but 
*before* Python attributes are cleared. So this really belongs in 
tp_clear().

Using a PyObject* attribute in the cdef class with manual reference 
counting is not a solution since this attribute could genuinely occur in 
a reference cycle.

So I would suggest to support a __clear__ special method, which would 
then be called both by tp_clear() and tp_dealloc(). It's important to 
note that this should be idempotent: it will be called at least once 
before Python attributes are cleared but it may also be called later.

PS: I never really understood the technical difference between 
tp_clear() and tp_dealloc(). It seems to me that these serve a very 
similar purpose: why can't the garbage collector just call tp_dealloc()?


Jeroen.


More information about the cython-devel mailing list