STINNER Victor <vstin...@python.org> added the comment:

> PyModule_AddObjectRef() is just Py_XINCREF() followed by PyModule_Add(). But 
> since most values added to the module are new references, Py_XINCREF() is 
> usually not needed.

There is no general rule. I saw two main cases.


(A) Create an object only to add it into the module. PyModule_Add() and 
PyModule_AddObject() are good for that case.

Example in the array module:

    PyObject *typecodes = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
    if (PyModule_AddObject(m, "typecodes", typecodes) < 0) {
        Py_XDECREF(typecodes);
        return -1;
    }

This code can be rewritten with PyModule_Add():

    PyObject *typecodes = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
    if (PyModule_Add(m, "typecodes", typecodes) < 0) {
        return -1;
    }

Py_XDECREF(typecodes) is no longer needed using PyModule_Add().


(B) Add an existing object into the module, but the objet is already stored 
elsewhere. PyModule_AddObjectRef() is good for that case. It became common to 
have this case when an object is also stored in the module state. 

Example in _ast:

    state->AST_type = PyType_FromSpec(&AST_type_spec);
    if (!state->AST_type) {
        return 0;
    }
    (...)
    if (PyModule_AddObjectRef(m, "AST", state->AST_type) < 0) {
        return -1;
    }

state->AST_type and module attribute both hold a strong reference to the type.

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue42327>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to