Can an object of a C type have random members added? tp_dictoffset?

G

Gregory Bond

One of the cool things about Python is the ability to "decorate" objects
with random extra members:
class C:
def __init__(self):
self.foo = 0
c = C()
c.bar = 1

I have a class implemented in C using tp_members to specify (read-only)
access to data members in the C struct. I'd like to be able to do the
decoration trick with objects of this class. Is this possible?

[The documentation for tp_dictoffset eseems to hint that this is
possible..... how do I use it?]
 
D

Denis S. Otkidach

On Thu, 21 Apr 2005 17:55:24 +1000 Gregory Bond wrote:

GB> I have a class implemented in C using tp_members to specify (read-only)
GB> access to data members in the C struct. I'd like to be able to do the
GB> decoration trick with objects of this class. Is this possible?
GB>
GB> [The documentation for tp_dictoffset eseems to hint that this is
GB> possible..... how do I use it?]

Something like the following:

typedef struct {
PyObject_HEAD
PyObject *dict;
} YourObject;

static PyMemberDef module_members[] = {
{"__dict__", T_OBJECT, offsetof(YourObject, dict), READONLY},
{0}
};

PyObject *
Your_New()
{
YourObject *obj;
obj = PyObject_GC_New(YourObject, &Your_Type);
if (obj==NUL) return NULL;
obj->dict = PyDict_New();
if (obj->dict==NULL) {
Py_DECREF(obj);
return NULL;
}
PyObject_GC_Track(obj);
return (PyObject *)obj;
}

PyTypeObject Your_Type = {
PyObject_HEAD_INIT(&PyType_Type)
# ...skipped...
offsetof(YourObject, dict), /* tp_dictoffset */
# ...skipped...
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top