dealloc function in python extend c module

Philip Semanchuk philip at semanchuk.com
Thu Jul 2 13:22:53 EDT 2009


On Jul 2, 2009, at 2:11 AM, Shen, Yu-Teh wrote:

> I create my extend type something like http://www.python.org/doc/current/extending/newtypes.html 
> .
> And my type has a member which is a pointer point to my allocate
> memory ( no ref count).
> ex:
> ---------------------------------------------------
> typedef struct {
>    PyObject_HEAD
>    /* Type-specific fields go here. */
>    mytype *p;
> } noddy_NoddyObject;
>
> And i write dealloc function like this:
> ---------------------------------------------------
> static void
> Noddy_dealloc(Noddy* self)
> {
>    delete p;
>    self->ob_type->tp_free((PyObject*)self);
> }
>
> And I found it's strange that it didn't call dealloc when there is no
> reference.
>
> ex:
> a = Noddy()
> b = a
> del a
> del b
> # i think there is no ref to the object, and it should call dealloc
> but it didn't call!!!
>
> could anyone tell me what happened?


Hi Shen,
I'm no expert on Python memory management, but since no once else has  
answered your question I'll tell you what I *think* is happening.

Python doesn't delete objects as soon as they're dereferenced. It  
merely marks them as safe for garbage collection (GC). If GC never  
happens (and it might not in a small test program), your dealloc  
function won't run.

Now some more knowledgeable person will probably correct me. =)

You can control the garbage collector manually with Python's gc  
module. You will probably never want to control the garbage collector  
manually in ordinary programs, but it can be useful for testing.


Hope this helps
Philip




More information about the Python-list mailing list