New submission from Serhiy Storchaka <storchaka+cpyt...@gmail.com>:

There is a design flaw in PyModule_AddObject(). It steals reference of its 
value only if the result is success. To avoid leaks it should be used in the 
following form:

    PyObject *tmp = <new reference>;
    if (PyModule_AddObject(name, name, tmp) < 0) {
        Py_XDECREF(tmp);
        goto error;
    }

It is inconvenient and many code forgot to use a temporary variable and call 
Py_XDECREF().

It was not intention, but it is too late to change this behavior now, because 
some code calls Py_XDECREF() if PyModule_AddObject() fails. Fixing 
PyModule_AddObject() now will break hard such code.

There was an idea to make the change gradual, controlled by a special macro 
(see issue26871). But it still has significant risk.

I propose to add new function PyModule_Add() which always steals reference to 
its argument. It is more convenient and allows to get rid of temporary variable:

    if (PyModule_Add(name, name, <new reference>) < 0) {
        goto error;
    }

I choose name PyModule_Add because it is short, and allow to write the call in 
one line with moderately long expression <new reference> (like 
PyFloat_FromDouble(...) or PyLong_FromUnsignedLong(...)).

----------
components: C API
messages: 380794
nosy: serhiy.storchaka, vstinner
priority: normal
severity: normal
status: open
title: Add PyModule_Add()
type: enhancement
versions: Python 3.10

_______________________________________
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