Adding and attribute to an instance
Gregory Bond
gnb at itga.com.au
Wed Aug 10 03:26:21 EDT 2005
J wrote:
> I have looked at some of the source code in PyObject_GenericGetAttr and
> it turns out that the object has no dictionary. It seens that the
> address of the dictionary is computed somehow via tp_dictoffset in the
> type object.
I asked this a few months ago......
Basically, you need a PyObject * in your object record:
struct PyStruct {
PY_OBJECT_HEAD
// ...
PyObject *dict;
// ....
}
then add the offset to the tp_dictoffset member in the type struct:
PyTypeObject PyType {
// ....
offsetof(PyStruct, dict), /* tp_dictoffset */
// ...
Make sure you init this member to 0 (tp_init), and make sure you
PyXDECREF() it when the object is deleted (tp_dealloc).
Optionally: add a __dict__ entry to the PyMemberDefs so that
obj.__dict__ works (tho this is not necessary):
{"__dict__", T_OBJECT, offsetof(PyStruct, dict), READONLY },
The ROOOOOOLY cool bit: You don't need to add the dictionary with
PyDict_New() etc, because the python runtime will create this dict the
first time a new attrribute is added. So the cost of this feature for
object instances that don't have extra attributes is just 4 unused bytes
in the instance record! This is just sooooooo cool.
Greg.
More information about the Python-list
mailing list