EMBEDDERS--REQUEST FOR COMMENTS:
mal at lemburg.com
Wed May 24 10:13:17 CEST 2000
> Here's a brief code snippet:
> static int ExampleObjectSetattr ( ExampleObject* self, char* name, PyObject* value )
> if (strcmp(name,"data")==0)
> if (PyString_Check(value))
> self->data = PyString_AsString(value);
You should copy the data instead of keeping a reference to it.
The reason is that the object value might get garbage collected
at some time in the future and then using the pointer will either
return munged data or simply cause a seg fault.
> return 0;
> PyErr_SetString(PyExc_AttributeError,"attempt to set data attribute to a value which is
> not a string");
> return -1;
> PyErr_SetString(PyExc_AttributeError,"attempt to set unknown attribute on non dynamic
> external type");
> return -1;
> My presumption is that, in this instance, I don't increase the reference count
> on the valuem because I've ascertained that it's a primitive (string, int, et
> However, if this were a real object, I'd be doing an INCREF() on it, and
> furthermore, would have to take care to do a DECREF() on what I was assigning
> Do I have this right?
No. Primitives are no different from any other object in Python.
The fact that some primitives are cached or shared can't be
relied upon, since these are implementation details of the
interpreter which may change in future versions of Python.
Python Pages: http://www.lemburg.com/python/
More information about the Python-list