Py_INCREF() incomprehension

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Tue Apr 26 18:08:58 CEST 2011


Am 26.04.2011 16:03, schrieb Hegedüs Ervin:

> I've read API doc (which you've included in another mail), but
> that's not clear for me. :(

No probem, I'll go in detail, now as I have read it again. (I didn't 
want to help from memory, as it is some time ago I worked with it, and 
didn't have time to read it.)

>> The most critical parts are indeed
>>
>> * the input parameters

The ownership rules say that the input parameter belongs to the caller 
who holds it at least until we return. (We just "borrow" it.) So no 
action needed.


>> * Py_BuildValue()

This function "transfers ownership", as it is none of 
(PyTuple_GetItem(), PyList_GetItem(), PyDict_GetItem(), 
PyDict_GetItemString()).

So the value it returns belongs to us, for now.

We do transfer ownership to our caller (implicitly), so no action is 
required as well here.


> so, it means when I implicit allocate a new object (whit
> Py_BuildValue()), Python's GC will free that pointer when it
> doesn't require anymore?

In a way, yes. But you have to obey ownership: whom belongs the current 
reference? If it is not ours, and we need it, we do Py_(X)INCREF(). If 
we got it, but don't need it, we do Py_(X)DECREF().


>> BTW: Is there any reason for using calloc()? malloc() would probably
>> be faster...
>
> may be, I didn't measure it ever... but calloc() gives clear
> space... :)

Ok. (But as sizeof(char) is, by C standard definition, always 1, you can 
write it shorter.)


Thomas



More information about the Python-list mailing list