This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: C API: Allocating Objects on the Heap. Misleading documentation.
Type: enhancement Stage:
Components: Documentation Versions: Python 3.9, Python 3.8
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: docs@python Nosy List: docs@python, igo95862
Priority: normal Keywords:

Created on 2020-11-08 18:21 by igo95862, last changed 2022-04-11 14:59 by admin.

Messages (2)
msg380558 - (view) Author: igo95862 (igo95862) Date: 2020-11-08 18:21
The issue is that the function names are too similar to other function that do completely different things.


`PyObject_Init` this function does not use `__init__` at all.
What it does is sets the already allocated object pointer to the specific type and increments its reference.


`PyObject_New` this function has nothing to do with `__new__`. It mallocs the new object and when calls `PyObject_Init` to set its type and increment reference.


Most importantly neither function actually calls `__init__`. You need to do it manually otherwise you might get garbage in your object data from residual memory.


I think there should be a small example showing how to allocate objects on heap and initialize them. This is what I do (ignore the names):


```
SdBusMessageObject *message_object = PyObject_NEW(SdBusMessageObject, &SdBusMessageType);
SdBusMessageType.tp_init((PyObject *)message_object, NULL, NULL);
```
msg380744 - (view) Author: igo95862 (igo95862) Date: 2020-11-11 09:18
I found out that you can call the type as an object in order to create new object.


Example:


SdBusMessageObject *new_message_object = (SdBusMessageObject *)PyObject_Call((PyObject *)&SdBusMessageType, dummy_tuple, dummy_dict);


This is somewhat not documented. Is this the recommended way to allocate object on heap?


I also found out that if you create a custom .tp_free function for the type it must call PyObject_Free(self); otherwise you leak memory.
History
Date User Action Args
2022-04-11 14:59:37adminsetgithub: 86458
2020-11-11 09:18:27igo95862setmessages: + msg380744
2020-11-08 18:23:43igo95862settype: enhancement
2020-11-08 18:21:38igo95862create