Py_INCREF() incomprehension

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Wed Apr 27 05:58:18 EDT 2011


Am 26.04.2011 20:44, schrieb Hegedüs Ervin:

> and (maybe) final question: :)
>
> I defined many exceptions:
>
> static PyObject *cibcrypt_error_nokey;
> static PyObject *cibcrypt_error_nofile;
> static PyObject *cibcrypt_error_badpad;
> ...
>
> void handle_err(int errcode) {
>      switch(errcode) {
>          case -1:    PyErr_SetString(cibcrypt_error_nokey, "Can't find key.");
>                      break;
> ...
> }
> ...
>      cibcrypt_error_nokey = PyErr_NewException("cibcrypt.error_nokey", NULL, NULL);
> ...
>      PyModule_AddObject(o, "error", cibcrypt_error_nokey);

Then I would not use the name "error" here, but maybe "error_nokey" or 
even better "NoKeyException".

Oops: there is an inconsistency in the docu: on the one hand, it says

   There are exactly two important exceptions to this rule:
   PyTuple_SetItem() and PyList_SetItem().

stating these are the only ones who take over ownership.

But PyModule_AddObject() claims to "steal" a reference as well...


> I am right, here also no need any Py_INCREF()/Py_DECREF() action,
> based on this doc:
> http://docs.python.org/c-api/arg.html

I'm not sure: On one hand, you pass ownership of the error objects to 
the module. There - one could think - they are until the module is unloaded.

But what if someone does "del module.NoKeyException"? In this case, the 
object could have been destroyed, and you are using it -> BANG.

On the other hand, if you keep one instance internally, it is not 
possible any longer to unload the module without a memory leak...


As already stated - you might want to have a look at some other C 
modules and mimic their behaviour... (and hope they are doing it right...)


Thomas



More information about the Python-list mailing list