dealloc function in python extend c module

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Jul 2 21:28:45 EDT 2009


En Thu, 02 Jul 2009 14:22:53 -0300, Philip Semanchuk
<philip at semanchuk.com> escribió:
> 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.

And you set the tp_dealloc field in the type structure to Noddy_dealloc,
did you?

>> 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!!!

You can use sys.getrefcount(a) to check how many references it has.
Remember that it returns one more than the value you expect (because the
function itself holds a temporary reference to its argument)

> 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.

Nope. CPython *does* destroy objects as soon as their reference count
reaches zero. It does not rely on garbage collection for that.

> 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.

The garbage collector is only used to recover memory from object cycles
(in the CPython implementation; Jython *does* use garbage collection for
"normal" object destruction too)

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

And now some more knowledgeable person will probably correct me. =)

-- 
Gabriel Genellina




More information about the Python-list mailing list