473,394 Members | 1,870 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

python extension: incref question


I am writing a python extension and have a question about reference
counting on an attribute I set. I am using standard boilerplate code
for defining a new type.

I implement the setattr methods, and want to set some numeric values
from within the extension code. I create the new GlyphObject and set
the attributes with

GlyphObject *gm;
gm = PyObject_New(GlyphObject, &Glyph_Type);
//handle error
gm->x_attr = NULL;
Glyph_setattr(gm, "width", PyInt_FromLong(self->face->glyph->metrics.width));
Glyph_setattr(gm, "height", PyInt_FromLong(self->face->glyph->metrics.height));

where

static int
Glyph_setattr(GlyphObject *self, char *name, PyObject *v)
{
if (self->x_attr == NULL) {
self->x_attr = PyDict_New();
if (self->x_attr == NULL)
return -1;
}

if (v == NULL) {
int rv = PyDict_DelItemString(self->x_attr, name);
if (rv < 0)
PyErr_SetString(PyExc_AttributeError,
"delete non-existing Glyph attribute");
return rv;
}
else {
return PyDict_SetItemString(self->x_attr, name, v);
}
}

http://www.python.org/doc/current/ex...shipRules.html states

PyDict_SetItem() and friends don't take over ownership -- they are
``normal.''

I infer from this that since a new ref is created by PyInt_FromLong,
and PyDict_SetItemString doesn't take ownership, that I should
decrease the reference count in my types dealloc function. Is this
correct?

Thanks,
John Hunter

Jul 18 '05 #1
2 1795
John Hunter <jd******@ace.bsd.uchicago.edu> wrote in message news:<ma**************************************@pyt hon.org>...
I am writing a python extension and have a question about reference
counting on an attribute I set.
...
I infer from this that since a new ref is created by PyInt_FromLong,
and PyDict_SetItemString doesn't take ownership, that I should
decrease the reference count in my types dealloc function. Is this
correct?


Mostly. You're right about the reference ownership (PyDict_SetItem
creates its own reference (see Python 2.3.3
Objects/dictobject.c:531)). However, I would recommend disposing of
the extra reference not in your type's dealloc function, but as soon
as you've sent the value to Glyph_setattr. Something along the lines
of:
---
PyObject *val = PyInt_FromLong(self->face->glyph->metrics.width);
if (val == NULL) {
return PyErr_NoMemory();
}
int gsetResult = Glyph_setattr(gm, "width", val);
Py_DECREF(val);
if (gsetResult == -1) {
...
}
---
That way, you will have disposed of the extra reference to val as soon
as it's no longer needed. In your type's dealloc function, you can
simply Py_XDECREF(self->x_attr), and x_attr will dispose of its own
reference to val.

If you were to wait to dispose of the extra reference until your
type's dealloc function were called, but in the meantime
Glyph_setattr(gm, "width", ...) were called again, the extra reference
to val would be lost in the shuffle.
Jul 18 '05 #2
>>>>> "David" == David Rushby <wo**********@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

Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Russell E. Owen | last post by:
I'm writing a C extension for numarray and am puzzled about the idiom for error handling. The documentation seems to say one should always decref an array after calling NA_InputArray, etc., to...
53
by: Stelios Xanthakis | last post by:
Hi. pyvm is a program which can run python 2.4 bytecode (the .pyc files). A demo pre-release is available at: http://students.ceid.upatras.gr/~sxanth/pyvm/ Facts about pyvm: - It's FAST....
3
by: Sudheer Gupta | last post by:
Hi, I am having trouble using C struct in python. Hope anyone can help me out ... Say, I have my C struct as typedef struct call { struct call *next;
3
by: dmoore | last post by:
Hi Folks: I have a question about the use of static members in Python/C extensions. Take the simple example from the "Extending and Embedding the Python Interpreter" docs: A simple module...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.