python extension: incref question

John Hunter jdhunter at ace.bsd.uchicago.edu
Mon Feb 23 12:26:54 EST 2004


>>>>> "David" == David Rushby <woodsplitter at rocketmail.com> writes:

    David> Mostly.  You're right about the reference ownership
    David> (PyDict_SetItem creates its own reference (see Python 2.3.3
    David> Objects/dictobject.c:531)).  However, I would recommend
    David> disposing of the extra reference not in your type's dealloc
    David> function, but as soon as you've sent the value to


Thanks for the suggestions.  Since I have to set a lot of these, I
wrote a macro.  

#define SETATTR(o,setattr_func,name,PyBuilder,val) \
{ \
PyObject *pval =PyBuilder(val);\
if (pval == NULL) {PyErr_NoMemory(); return NULL;}\
int gsetResult = setattr_func(o, name, pval);\
Py_DECREF(pval);\
if (gsetResult == -1) {\
      PyErr_SetString(PyExc_RuntimeError, "Could not set attr");\
    return NULL;\
}\
}

(for some reason my compiler issued warnings on the return
PyErr_NoMemory() you suggested (incompatible return type) which is
surprising since PyErr_NoMemory returns NULL.  Maybe a macro issue?

which I use like

  SETATTR(self, FT2Font_setattr, "postscript_name", PyString_FromString, ps_name);
  SETATTR(self, FT2Font_setattr, "num_faces",       PyInt_FromLong,      self->face->num_faces);

Do you see any problems with this approach?

Also, I was surprised to find that these attrs don't automagically
appear in a dir(myobj).  I've been planning to consult the docs or
google since I'm sure it's a relatively obvious thing I'm missing, but
I thought I'd mention it while I had your ear :-).

JDH




More information about the Python-list mailing list