[Q] Extension: Refcount for exception types

  • Thread starter Ames Andreas (MPA/DF)
  • Start date
A

Ames Andreas (MPA/DF)

Hi all,

I'm currently building an extension module by hand and am confused by
the fact that as well xxmodule.c as structmodule.c and other examples
increment the refcount of the exception type(s) they are defining.
I. e. from xxmodule.c:

if (ErrorObject == NULL) {
ErrorObject = PyErr_NewException("xx.error", NULL, NULL);
if (ErrorObject == NULL)
return;
}
Py_INCREF(ErrorObject);
^^^^^^^^^^^^^^^^^^^^^^^ I mean this one.
PyModule_AddObject(m, "error", ErrorObject);

I know that PyModule_AddObject steals a reference, but now
ErrorObject's refcount should be 2, isn't it? I just fail to see
how the refcount can return to 0. I'm sure this is simple to explain,
so please enlighten me, why this isn't a leak.


cheers,

aa
 
?

=?windows-1252?Q?=22Martin_v=2E_L=F6wis=22?=

Ames said:
Py_INCREF(ErrorObject);
^^^^^^^^^^^^^^^^^^^^^^^ I mean this one.
PyModule_AddObject(m, "error", ErrorObject);

I know that PyModule_AddObject steals a reference, but now
ErrorObject's refcount should be 2, isn't it? I just fail to see
how the refcount can return to 0. I'm sure this is simple to explain,
so please enlighten me, why this isn't a leak.

It is a leak, but that is intentional. If the INCREF was not there,
and somebody would delete "error" from the dictionary, then the
error class would go away, and ErrorObject would be a dangling pointer.

Since the module C code refers to the exception through ErrorObject,
it must keep a reference that cannot go away. This is indeed a leak
because there is no module shutdown code which could decref ErrorObject,
and set it to NULL.

Regards,
Martin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top